djmzfKnm
djmzfKnm

Reputation: 27195

How to combine RewriteCond in htaccess

I am looking for If, else type of code which can combine my re-write rules based on host/domain name. So if domain name is "domainA" then redirect a to b, c to d and if domain name is "domainB" then redirect x to y and z to p. Basically I don't want to write the Condition again and again as I have done below:

I have written following code for htaccess

    RewriteCond %{HTTP_HOST} ^domain\.com$ [OR]
    RewriteCond %{HTTP_HOST} ^www\.domain\.com$
    RewriteRule ^home /? [L,R=301]

    RewriteCond %{HTTP_HOST} ^domain\.com$ [OR]
    RewriteCond %{HTTP_HOST} ^www\.domain\.com$
    RewriteRule ^home-old /? [L,R=301]

In above I am using host because I have multiple domains pointed to same hosting space so htaccess is common between all.

Can I combine the above multiple condition for a domain into one, instead of writing domai name again and again for some set of redirects for specific domain?

Please advise, thanks!

Upvotes: 0

Views: 2131

Answers (1)

Jon Lin
Jon Lin

Reputation: 143906

There really is no such if-then-else structure in mod_rewrite. You have to either be clever with your rules (which sometimes makes them unreadable or impossible to amend) or just be explicit about everything.

For your specific example, you can just use regular expressions to combine them:

^domain\.com$ and ^www\.domain\.com$ gets turned into ^(www\.)?domain\.com$

and

^home and ^home-old is just ^home, since the first only matches if the URI starts with home, and home-old does indeed start with home (there is no $ symbol to indicate the end of the string). So you're looking at:

RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC]
RewriteRule ^home /? [L,R=301]

If you need to be specific by using the $, you can just change the regex to:

RewriteRule ^home(-old)?$ /? [L,R=301]

EDIT:

If I have some other urls instead of home, and botique, and hairtips then I need to write RewriteCond every time? I guess I have to write that every time just confirming from you

Yes, you have to repeat the condition every time, or, you can make a passthrough at the very beginning of your rules:

RewriteCond %{HTTP_HOST} !^(www\.)?domain\.com$ [NC]
RewriteRule ^ - [L]

This means: anything that's not a request for host: www.domain.com or domain.com, then pass through without rewriting. Then you can just have rules after this because only requests with hosts other than the above will reach those rules.

This is the "clever" bit that I was referring to before. This can make it tricky to change your rules or amend them later because you've set a strict condition at the top.

Upvotes: 1

Related Questions