envysea
envysea

Reputation: 1031

How can I make this .htaccess redirect exclude the home page?

I have this setup:

http://example.com
http://www.example.com

and

http://www2.example.com

I would like to redirect all pages from the first set, except the homepage, to the newer (www2) domain.

Here's what I have in my .htaccess now:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} !www2.example.com$ [NC]
    RewriteRule ^(.*)$ http://www2.example.com/$1 [L,R=301]
</IfModule>

This works, but I want to exclude the homepage. How can I add the additional condition for that?

Edit: Also, I would like to exclude a folder called "assets" and all of it's contents.

Upvotes: 1

Views: 829

Answers (1)

Jon Lin
Jon Lin

Reputation: 143886

You can just change your regex to .+, which means at least one or more of ., where the . can be anything:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} !www2.example.com$ [NC]
    RewriteRule ^(.+)$ http://www2.example.com/$1 [L,R=301]
</IfModule>

The reasoning here is that the home page (request URI = /) will have the slash stripped and actually be an empty string, which .* matches. But if you have .+, the empty string (home page) won't match.

If the homepage is something other than just / (like, /home.html) then you can exclude it like this:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_URI} !^/home\.html
    RewriteCond %{HTTP_HOST} !www2.example.com$ [NC]
    RewriteRule ^(.*)$ http://www2.example.com/$1 [L,R=301]
</IfModule>

Upvotes: 1

Related Questions