Last Updated on January 20, 2022 by Amit

In this article I will show you how to write a RewriteRule for htaccess to redirect a website to another website with homepage exception.
I will show you a RewriteRule that does a 301 redirect from your website to another external site. The redirection will get applied to all URLs on your website except the homepage /.

If you are new to htaccess , you can follow our basic htaccess guide .htaccess tutorial for beginners .

Before we get to the rule, let’s first understand the requirement :
Suppose, we have two domains

  • example1.com
  • example2.com

Both domains are on different webservers, and we want that all traffic from example1.com should get redirected to example2.com with homepage exception meaning that the “example1.com/” will not get redirected to example2 domain while all other URLs ie: “example1.com/*” will use the redirection.

There are two different ways to do such redirection with an htaccess file.You can either use mod-rewrite or mod-alias. These two Apache modules can be used for URL redirection on Apache.

Redirect domain with homepage exception using RedirectMatch

One of the easiest way to do this type of redirection with htaccess is a simple one liner RedirectMatch directive. This directive is part of Apache mod-alias. You can use the code below in your htaccess file :

RedirectMatch 301 ^/(.+)$ https://example.com/$1

RedirectMatch directive use regular expression based pattern so the match becomes easier. The code above will redirect all requests except the homepage from your example1 domain to the another domain.

Note : The code should be placed in root htaccess in your example1 domain.

If you want to remove the homepage exception, just change the regex pattern to ^/(.*)$ .

Redirect domain with homepage exception using RewriteRule

You can redirect your domain with RewriteRule directive. RedirectMatch can fail to work if your htaccess contains other directives, in that case RewriteRule is the solution. Just place the code at the top of your htaccess file :

RewriteEngine On
RewriteRule ^(.+)$ https://example2.com/$1 [R=301,L]

In case your destination domain is on the same server and pointing to the same document root then both the Redirects I showed above might cause an infinite redirect error. Use the following rule if both domains are on the same server :

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?example1\.com$
RewriteRule ^(.+)$ https://example2.com/$1 [L,R=301]

I hope this article was helpful, if it really helped you and you want to say thanks just click on the coffee button below to buy me a coffee. Thanks.

How useful was this post?

Click on a star to rate it!

Average rating 4.4 / 5. Vote count: 9

No votes so far! Be the first to rate this post.