[dev] htaccess: redirect a domain or multiple domains

The snippet below is excellent if you have several domains pointing to the same webspace and only want to use one domain as your primary domain.

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

Explanation of the code

Make sure this code is in your htaccess file in the root of the webspace.

  • The first two lines tell apache to handle the current directory and start the rewrite.
  • The next line RewriteCond %{HTTP_HOST} !newdomain.com$ specifies that the next rule only fires when the http host (that means the domain of the queried url) is not (- specified with the “!”) newdomain.com.
  • The $ means that the host ends with newdomain.com – and the result is that all pages from newdomain.com will trigger the following rewrite rule. Combined with the inversive '!' is the result every host that is not newdomain.com will be redirected to this domain.
  • The [NC] specifies that the http host is case insensitive.
  • The escapes the '.' – becaues this is a special character (normally, the dot (.) means that one character is unspecified)
  • The final line describes the action that should be executed:
    RewriteRule ^(.*)$ http://www.newdomain.com/$1 [L,R=301]
    The ^(.*)$ is a little magic trick.
    So .* means that you can have a lot of characters, not only one. This is what we need – because this ^(.*)$ contains the requested url, without the domain. The next part http://www.newdomain.com/$1 describes the target of the rewrite rule – this is our “final”, used domain name, where $1 contains the content of the (.*).
  • The next part is also important, since it does the 301 redirect for us automatically:
    [L,R=301]
    L means this is the last rule in this run – so after this rewrite the webserver will return a result. The R=301 means that the webserver returns a 301 moved permanently to the requesting browser or search engine.

About us

E:

We are a web development agency located in Cape Town, South Africa. We design great looking websites. We are CSS enthusiasts. We specialise in Content management systems. We are a professional Team with over 30 years of experience. Learn more.

linkedin Google+ twitter linkedin

Office South Africa

E: za [AT] raramuridesign [DOT] com
T:
 +27 21 913 7872 
F: +27 86 756 6999
Mon - Fri 09h00-16h30 (ZA)