Category Archives: websites

Apache mod_rewrite Redirecting Directories Without Looping

Wow! It’s true what they say, mod_rewrite rules are a dark art, and whilst I’ve combed the Internet to find, what I thought would be a simple redirect, I’ve found countless examples that didn’t work.
So now I have one that does work I’m sharing.

Goal

To redirect hits to a subdomain sshwindows.webheat.co.uk to a subdirectory (in my case cause that is the link to the page within my wiki) /display/sshwindows/

Traffic to any other domain hosted on this same server should not be redirected.

All without looping.

Solution

Check two conditions not just one. Check the host header and the uri to ensure the root had been hit, and only then redirect.

Code

RewriteEngine On
RewriteCond %{HTTP_HOST} ^sshwindows\.webheat\.co\.uk$ [NC]
RewriteCond %{REQUEST_URI} /$
RewriteRule ^(.*)?$ http://sshwindows.webheat.co.uk/display/sshwindows [L]

For me I put this into my /etc/apache2/sites-enabled/000-default file, but you can equally put this into a .htaccess file. For me this was to be a global thing.

Additional Notes

The [nc] is the no-case flag to make the host header match case-insensitive.
The [L] is the Last flag, so after this rule no further ones will be processed. In all honesty I don’t need this here, but that part came from another source and it’s 4am so I’ll be damned if I’m going to remove it now when it’s all working :-)

Share