Htaccess Subdomains to www

Last Updated: Feb. 17th 2022 at 6:18pm Tags: apache blog domains htaccess

Search engines are making duplicate content an easy problem to solve.

Search engines are making duplicate content an easy problem to solve. This article outlines the htaccess method I use to redirect my sub domains to www.

I like to forward all my domains to the www sub-domain, here are a few reasons why:

  • Eliminate duplicate content in search engines
  • Remove confusion in CMS Control panels and sessions
  • Reduce confusion with DNS and CDNs

The code

This is the code I place in my htaccess file.

RewriteEngine On
RewriteBase /

# Redirect sub-domains to www
# v1.3
# Last Updated: Sept. 18, 2013

rewritecond %{HTTP_HOST} !^www\.nickyeoman\.com$ [NC]
rewriterule ^(.*)$ https://www.nickyeoman.com/$1 [R=301,L]

Please note the exclamation mark means not, the backslashes escape the periods, and the NC means case-insensitive. L means last rule (stop rewriting after this).

Logical And

I used do web development on my local machine and set a sub-domain (dev.mydomain.com) using the etc/hosts file.
The above code snippet completes a logical and until the rewriterule is reached. I now use tlds instead of subdomains so you can use simple pipes in your code like so:

rewritecond %{HTTP_HOST} !^www\.nickyeoman\.com$ [NC]
rewritecond %{HTTP_HOST} !^www\.nickyeoman\.(com|ca|tld)$ [NC]

Redirect www domain to non-www domain

Maybe you are a small company and don’t require the use of the www sub-domain.
If this is the case you can use htaccess to redirect a www domain to a non-www domain. This is also known as the TLD or Top Level Domain.

I prefer the above method of forwarding to the World Wide Web (www) sub domain.

The code

RewriteEngine On
RewriteBase /

# Redirect www to non-www
# v1.1
# Last Updated: Nov 13, 2012

# permanently redirect from www domain to non-www domain
RewriteCond %{HTTP_HOST} ^www\.nickyeoman\.com$ [NC]
RewriteRule ^(.*)$ https://nickyeoman.com/$1 [R=301,L]

Reference

Comments

You need to login to comment.