Generic non-www to www (and vice versa) 301 redirect using .htaccess

November 3, 2008 – 4:33 pm

The problem:

I’ve always hardcoded the domain name in my htaccess’es, requiring me to make changes each time I deploy a new website.

The solution:

Behold, an alternate, generic method of redirecting non-www to www and www to non-www, requiring no changes between deployments!

Non-www to www

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

www to non-www

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

Bonus tip: Remove trailing slash from address line

RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]

Tags: , , ,

  1. 7 Responses to “Generic non-www to www (and vice versa) 301 redirect using .htaccess”

  2. Nice one! I did the same for couple of projects but this is much better

    By primeminister on Feb 13, 2009

  3. and for someone who accidentally forgot to turn off caps-lock:

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

    By primeminister on Feb 13, 2009

  4. Good solution. htaccess is a wonderful thing is it not! I really should get a list of these together for quick reference..

    By Robin on Jun 20, 2009

  5. Apart the hardcoding of the domain, what if we cannot use .htaccess?

    Is this PHP solution leading to the same solution?

    $uniqueHost = ‘www.myWebSite.com’;
    if (isset($_SERVER["HTTP_HOST"])) {
    if ($_SERVER["HTTP_HOST"] != $uniqueHost) {
    if (isset($_SERVER["REQUEST_URI"])) {
    $redirect = ‘http://’.$uniqueHost.$_SERVER["REQUEST_URI"];
    }
    else {
    $redirect = ‘http://’.$uniqueHost;
    }
    header(“HTTP/1.1 301 Moved Permanently”);
    header(“Location: “.$redirect);
    exit;
    }
    }

    By GiB on Jun 22, 2009

  6. For the people that don’t understand what this page is about, allthough it is highly precious stuff. Each website has 2 different URL’s, with the www in front, and also without www, searchengines see these as two different pages, that means by re-direct one of them to the other, you can effectively consolidate all of your link popularity to a single URL.

    By Paginas Web Lima on Jul 4, 2009

  7. Thanks so much about that tip for taking the caps lock off when they type it that way. It wasn’t working for users with caps lock on. Really helpful.

    By tim on Aug 16, 2009

  8. You can make exceptions to directories using: RewriteCond %{REQUEST_URI} !^/directory_name/

    By web slc on Nov 6, 2009

Post a Comment