13 May 2010

Universal ALL DOMAIN rewrite for non-www to canonical/www using htaccess or https.conf on apache server


This took me a few days to get right. The lack of feedback from testing, along with browser caching and the general head wrecking-ness of Regex make htaccess rewrites like this a total pain in the ass. Anyway thanks to the guys over at the alt.apache.configuration newsgroup, I've managed this:

The code below will rewrite anything on your server that does not have a www. at the beginning to the same thing with a www. prefixed. Urls beginning with an IP address are left alone so that http://IPADDRESS/~username/ access still works.

Subdomains are also redirected to their www. equivalent however they should still resolve and work normally. (untested)

This is great if you run your own server and want to redirect everything at once or if you just want a template that you can use for all your websites without editing or altering.

My code works without too much Regex with makes it a lot less memory intensive than most "universal" mod_rewrites out there.

The code below works on APACHE servers.



The code can go in a file named .htaccess (yes that's an empty filename with a dot htaccess extension) in the root directory of your website like so:
Please see right hand pane before copying >>>
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ![0-9]{1,3}\.[0-9]{1,3}\.
RewriteRule !"" http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NC]

Or if you have access to httpd.conf - the apache configuration file, the following will be much easier on the server.* Just add this at the bottom of /etc/httpd/conf/httpd.conf ** and restart.
Please see right hand pane before copying >>>
<Directory /home/*>
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ![0-9]{1,3}\.[0-9]{1,3}\.
RewriteRule !"" http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NC]
</directory>
* The htaccess version is parsed every time the server is accessed while the httpd.conf version is parsed once when the server is started up.
** These paths and instructions work on my VPS running Ubuntu. The paths might be different for other distributions.

No comments:

Post a Comment

Cron Design Studio: Dublin based web design & software development