Redirect non-www to www or vice versa with .htaccess or Apache or Nginx

Something we always have to do with new or old sites is add, for Florida SEO purposes, a redirect of non-www to www, or www to non-www ( instead of The reason being, Google sees and as two different sites and we’d get penalized for having duplicate content should someone put out a link to our site using one or the other.

The solution being, choose which one you want to have redirect – non-www to www or www to non-www. The choice is yours. It’s really just a personal preference for me to not use www in front of my domain.

non-www to www

If you already have redirects in place, just place this in your code somewhere:
The preceding two solutions are really generic. You can place them in your .htaccess without modification. How about www to non-www?

www to non-www

Again, the preceding solution is generic and you can copy and paste it into your .htaccess file without modification. Unless of course you have some crazy kind of configuration. And if that’s the case, comment on this page and I’ll find a solution for you (as time permits).

Keep in mind, using %{HTTP_HOST} when you have different domains pointing to the same web root, will cause problems. In that instance, just use your primary domain.

What about Nginx?

Nginx is is almost as popular as Apache for serving web content. Here’s how to do it with Nginx:

With any server side config file, you have to start the webs server.


You’ve learned how to add, in your .htaccess file, a redirect for non-www to www domains. You’ve also learned how to redirect www to non-www. Furthermore, you’ve learned two reusable ways of doing what you wanted to do.

  1. Adam Reply


    Thanks for the tutorial.

    My scenario is www to non-www so I tried;

    # Redirect www to non-ww
    RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
    RewriteRule ^(.*)$ http://%1$1 [R=301,L]

    The rewrite occurs but with 2 trailing backslash like this

    This generates a 404

    Please advise how I can resolve, thanks again

    • The Barton Reply

      You can do this:

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


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

Leave a comment

Find the Best SEO in Fort Lauderdale, Florida (Plantation SEO) | Drupal & Worpress Develpment