camcam camcam - 1 month ago 9
Apache Configuration Question

How to get mod_rewrite working for requests of images which are located in aliased directories?

I have xampp with apache 2.4.9 on windows 10.

In httpd-vhosts.conf there is a definition of a virtual host with alias:

<VirtualHost *:80>
DocumentRoot "I:/xampp/htdocs/mysite"
ServerName dev.mysite
Alias "/sites/default/files/myimages" "C:/anotherdir/myimages"
<Directory "C:/anotherdir/myimages">
Require all granted
</Directory>
</VirtualHost>


In httpd.conf the LogLevel is set:

LogLevel warn mod_rewrite.c:trace8


The .htaccess located in the virtual host's root directory contains only these lines and nothing else:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^$
RewriteRule .*\.(gif|jpg|png)$ /404.html [L]
</IfModule>


When I type into the browser address bar a request for an image which is on a normal (not aliased) path, e.g.
http://dev.mysite/sites/default/files/content/image1.jpg
, I get the content of 404.html file on the screen and a few lines in error.log resulting from mod_rewrite. That's expected.

But when I type in the same browser address bar a request for an image which is on the aliased path, e.g.
http://dev.mysite/sites/default/files/myimages/image2.jpg
, I get the real image and there are no new lines in error.log. That's bad, I'd like to see the 404.html as well.

So how to use mod_rewrite for files on aliased directories?

Answer

As you have said you have added a .htaccess inside the virtualhost documentroot, but an alias path is pointing to another path somewhere else out of the scope of that directory.

The key to all these are, different physical paths, and alias is a virtual path inside another path, and you don't even have AllowOverride all in that path, so it should never be used.

So first, do not use .htaccess because you don't need it.

And then , define the rewriterule in virtualhost context and you will see it will work.

<VirtualHost *:80>
    DocumentRoot "I:/xampp/htdocs/mysite"
    ServerName dev.mysite
    Alias "/sites/default/files/myimages" "C:/anotherdir/myimages"
    <Directory "C:/anotherdir/myimages">
        Require all granted
    </Directory>
    RewriteEngine on
    RewriteCond %{HTTP_REFERER} ^$
    RewriteRule \.(gif|jpg|png)$ /404.html [L]
</VirtualHost>