Apache rewrite for particular file requests

Viewed 59

I'm trying to setup Apache to rewrite particular file names when requested under a virtual host. The goal is to change certain branding elements based on the host header used (all of which have virtual host configs).

I had this working in nginx as per the example below

if ($host = "test.example.com") {
    rewrite ^/images/file1.png$ /images/otherfile1.png;
    rewrite ^/images/file2.png$ /images/differentfile2.png;
    break;
}

For Apache I used the following config in the virtual hosts file, and confirmed the module is running, but it does not seem work (the original file1 is used).

<Directory "/opt/site/html/">
     AllowOverride All
     Options FollowSymLinks MultiViews
     Require all granted
   RewriteEngine On
   RewriteBase /
   RewriteRule ^/images/file1.png$ /images/otherfile1.png
   RewriteRule ^/images/file2.png$ /images/differnetfile2.png
   </Directory>

Any advice on what I'm missing to enable this rewrite would be greatly appreciated.

1 Answers
RewriteRule ^/images/file1.png$ /images/otherfile1.png
RewriteRule ^/images/file2.png$ /images/differnetfile2.png

These directives are inside a <Directory> container (inside a <VirtualHost>). In a directory context (as with .htaccess), the URL-path matched by the RewriteRule pattern does not start with a slash. So the above rules will not match. The directives should be like this instead:

RewriteRule ^images/file1\.png$ /images/otherfile1.png [L]
RewriteRule ^images/file2\.png$ /images/differnetfile2.png [L]

NB: Don't forget to backslash-escape literal dots in the regex and you should use the L flag here to stop further processing by the rewrite engine.

Alternatively, you can move these rules out of the <Directory> wrapper and into the <VirtualHost> container directly. In this context, the rules match against the full root-relative URL-path, starting with a slash (as you have written). But in a virtualhost context, the RewriteBase directive is not permitted so must be removed (you are not making use of this anyway).


Aside:

AllowOverride All
Options FollowSymLinks MultiViews

You are allowing .htaccess overrides (first directive). Note that if you do have an .htaccess file with mod_rewrite directives (RewriteRule etc.) then these will completely override the directives in the corresponding <Directory> container in the server config. You may want to explicitly disable .htaccess overrides, for example:

AllowOverride None

You've also enabled MultiViews - is that intentional? This basically enables extensionless URLs out-of-the-box (on everything) and can potentially conflict with mod_rewrite, so generally, this should be disabled. Simply remove it from the above rule to disable this, for example:

Options FollowSymLinks
RewriteBase /

You're not actually using this in the directives you've posted.

Related