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
Technically a simple
AliasMatch ^/$ display/sshwindows
should be enough, provided that display/sshwindows is relative to your document root dir. If not, use absolute path. Another option is to make diplay/sshwindows your DocumentRoot/ServerRoot, depends whether you host a single site or multiple vhosts.
If you absolutely require redirection (and btw, atm confluence makes another one, after yours) why not simplify the rewriterule such as:
RewriteCond %{HTTP_HOST} ^sshwindows\.webheat\.co\.uk$
RewriteRule ^/?$ http://sshwindows.webheat.co.uk/display/sshwindows? [L,R=301]
or even
RewriteRule ^/?$ http://sshwindows.webheat.co.uk/display/sshwindows/OpenSSH+for+Windows [L,R=301]
Notes: NC (NoCase) is irrelevant here as apache canonicalises the url before handling it to mod_rewrite. The second rewritecond is irrelevant since you have only 1 regex to match against the URI path and this can be done in the RewriteRule itself. And last and final note: use “?” in the end, unless you want to preserve any query strings, and use permanent redirect, as using temporary one (permanently) is a bad practise.
P.S. If you have a fairly recent apache and mod_rewrite you could use QSD flag as well, check out
http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsd
Cheers!
http://httpd.apache.org/docs/2.2/rewrite/avoid.html
Just use RedrectMatch
Bad news – it looks like it’s getting into a loop at the moment!
Bugger :-/