Published: 8th Mar 2018 | Words: 315 | Reading Time: 2 minutes


Forcing www or non-www redirects

Using a .htaccess rule you can easily redirect to your correct domain with or without the www. Doing this improves your SEOThe .htaccess rules below set a 301 redirect, which is permanent redirect between the two domains. You can use things like Google search console and Google Analytics to see information about domains recieving traffic and create a list of domains to 301 redirect. If your chossing between using or not using the www, its probably best not to use it. Having a shorter domain provides benefits when you find yourself character limited and wanting to include a URL somewhere. 

How to redirect www URLs to non-www?

The first line below sets the rewrite base. This is optional and if you are using it, it only needs to be set once at the top of your .htaccess file. If you don't use rewrite base this rule will be slightly different ^/(.*)$

The second line uses regular expression to check the hostname and see if it starts ^ with www., the back slashes are to escape the dots because these have special meaning in regular expression.

The third line takes the entire path (.*) and appends it as $1 after the protocol + hostname to redirect to.

RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.ddmseo\.com$ [NC]
RewriteRule ^(.*)$$1 [L,R=301]

How to redirect non-www URLs to www?

Both redirect rules are fairly similar, one is just the opposite of the other really. You can redirect to the www version by checking if the current host does not start with www. The rules here are extremely similar to the one above. The only real difference is the second line. Instead of checking for the www version of the domain, we check for the non www version.

RewriteBase /
RewriteCond %{HTTP_HOST} ^ddmseo\.com$ [NC]
RewriteRule ^(.*)$$1 [L,R=301]