Redirect WWW to Non-WWW and Vice Versa via HTACCESS

If you want to redirect all URLs on your site that contain www to the non-www version (e.g. http://www.my-domain.com to http://my-domain.com), add the following code to your .htaccess file:


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

If you want to do the opposite – redirect non-www URLs to the www version – use this code:


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

Why do this?

  • Prevents Google from treating these as two separate URLs (duplicate content).
  • Prevents your page ranking from being split across two URLs.
  • It is cleaner and more consistent.

Migrating a WordPress site to HTTPS is no small matter – see the guide Migrating to HTTPS on WordPress sites.

Discussion
[  0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!