Redirect www to non www

Redirect www to non www

RewriteCond %{HTTP_HOST} ^www.htmlviewer.net [NC]
RewriteRule ^(.*)$ https://blog.htmlviewer.net/$1 [L,R=301]

Redirect non www to www

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

As stated in the apache mod rewrite documentation, the server's variable - HTTP_HOST holds the name of the domain.Thus, the RewriteCond directive checks if the domain name starts (^ sign) with 'www.htmlviewer.net'. The [NC] flag stands for 'NoCase', so www.htmlviewer.net will be treated same as www.htmlviewer.net

The second directive - RewriteRule is doing the redirect. The [L] flag tells that this is the last rule and the [R=301] flag tells to do a permanent redirect.

How it works?

When the user types your domain with www, for example www.htmlviewer.net, it will be redirected to htmlviewer.net. Even if he access a page, it will be redirected to the same page without the www. Example: www.htmlviewer.net/redirect-www-to-non-www will redirect to htmlviewer.net/redirect-www-to-non-www. You can check this with the article you are currently reading.

You can use the same configuration for any other subdomain.

RewriteCond %{HTTP_HOST} ^dev.htmlviewer.net [NC]
RewriteRule ^(.*)$ https://blog.htmlviewer.net/$1 [L,R=301]
- Posted by Eva to Apache