Linux – Apache, mod_rewrite and symlinks/aliases

apache-2.2linuxmod-rewriteUbuntuunix

I'm trying to force the adding of www. if visiting my site.
I've added the following to my site conf file:

<Directory /var/www/main>
    Options FollowSymlinks
    RewriteEngine on
    RewriteCond %{HTTP_HOST}   ^example\.com
    RewriteRule ^(.*)∞         http://www.example.com/$1 [L,R=permanent]
</Directory>

which works great when accessing example.com.

But if I make a symlink ln -s /path/to/somewhere foo and I try to access example.com/foo I doesn't get redirected to www.example.com/foo which is of course as expected since /path/to/somewhere is not in /var/www/main

Do you have any suggestions on how to make it work with symlinks as well?

Best Answer

You're hitting the difference between Directory and Location directives in Apache. According to the documentation, Directory applies to filesystem-space, and Location applies to web-space. Try breaking your configuration block up like so:

<Directory /var/www/main>
  Options FollowSymLinks
</Directory>
<Location />
  RewriteEngine on
  RewriteCond %{HTTP_HOST} ^example\.com
  RewriteRule ^(.*) http://www.example.com/$1 [L,R=permanent]
</Location>

...in other words, pull the rewrite section out into a Location block.

Related Topic