Dynamically redirect non-www to www (or vice versa) without hardcoding using .htaccess

After much searching and testing, this is what I’ve up up with:

Redirect www to non-www

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

Redirect non-www to www

RewriteCond %{HTTP_HOST} !^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://www\.%{HTTP_HOST}/$1 [R=301,L]

or

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(.+)$ [NC]
RewriteRule ^(.*)$ http://www\.%1/$1 [R=301,L]

Related Posts:

  • No Related Posts
This entry was posted in Tech Tips, Web Development and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *