htaccess: redirect a domain or multiple domains

Managing multiple domains pointing to the same webspace can be a challenge, especially when you want to designate one domain as the primary domain. In this blog post, we'll explore a code snippet that simplifies domain redirection using Apache's Rewrite Rules.

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

Or, if you prefer to exclude the "www" subdomain:

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

Explanation of the Code

To implement this code, ensure that it resides in the .htaccess file located at the root of your webspace. Let's break down the code snippet to understand how it works:

  1. The first two lines, RewriteEngine On and RewriteBase /, instruct Apache to handle the current directory and initiate the rewrite process.

  2. The line RewriteCond %{HTTP_HOST} !newdomain.com$ specifies that the following rule should only be applied when the HTTP host (i.e., the domain of the requested URL) is not newdomain.com. This condition allows the rule to redirect all pages from domains other than newdomain.com.

  3. The [NC] flag makes the HTTP host comparison case-insensitive.

  4. The ^ character in ^(.*)$ escapes the dot (.) since it has a special meaning in regular expressions. Here, (.*) captures the requested URL without the domain, which is exactly what we need.

  5. The http://www.newdomain.com/$1 specifies the target URL for the rewrite rule. $1 represents the captured content from (.*), effectively appending the requested URL to the new domain.

  6. The [L,R=301] flags indicate that this is the last rule to be executed (L), and it should result in a 301 moved permanently redirect (R=301) being sent to the browser or search engine.

Conclusion

Managing multiple domains and selecting a primary domain is made easier with Apache's Rewrite Rules.

By implementing the code snippet provided, you can effortlessly redirect all requests from secondary domains to your desired primary domain. This ensures a consistent user experience and streamlines the management of your web presence.