Skip to main content

Add www to URL using Apache mod_rewrite

Submitted by amitsedai on
For sites belonging to a domain name(Not Subdomain), one can access the site using the domain name with www, Ex: www.example.com or without it: example.com Both ways the site can be accessed when a ServerAlias is created in the config. However this is confusing as session information for both is different, which means if one is accessing the site with www preceded and logs in, on accessing the site without www preceded - the server would have no information saved. To redirect any domain name to use www by default, the following mod_rewrite condition can be used: RewriteEngine On

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

For Redirecting from a site to another can also be achieved RewriteEngine On

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^site1.example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com$1 [R=301,L]

-- Source: http://stackoverflow.com/questions/7493241/mod-rewrite-add-www http://www.howtoforge.com/the-useful-uses-of-mod_rewrite http://www.phatz.com/301redirect.php