Search code examples
apache.htaccesshttp-redirectmod-rewriteurl-rewriting

Matching HTTP_HOST in rewriteCond?


I have two servers that are running for my app.

prod and staging as below.

I need to execute some redirect rule if the HTTP_HOST matches www.sitedomain.com or stage.sitedomain.com

if the URL is https://www.sitedomain.com/us-en page should redirect to https://www.sitedomain.us/

and if the URL is https://stage.sitedomain.com/us-en page should redirect to https://stage.sitedomain.us/

I am executing the following steps

RewriteCond %{HTTP_HOST} ^www\.sitedomain\.com$ [NC]                                  1
RewriteRule ^/us-en/(.*)$   https://www.sitedomain.us/$1      [R=301,L,NC]            2

RewriteCond %{HTTP_HOST} ^stage\.sitedomain\.com$ [NC]                                 3
RewriteRule ^/us-en/(.*)$   https://stage.sitedomain.us/$1      [R=301,L,NC]           4

The problem is whenever I am hitting https://stage.sitedomain.com/us-en I am redirecting to https://www.sitedomain.us/, not to https://stage.sitedomain.us (simply saying it never reaches line Number 3)

So line number 1 always executing as True, and rewrite rule at line2 executing for stage URL.

Can anyone help me to solve this??


Solution

  • With your shown samples, could you please try following. Make sure this is the very first rule of your htaccess Rule file. Please clear your browser cache before testing your URLs.

    RewriteEngine ON
    RewriteCond %{HTTP_HOST} ^(www|stage)\.(sitedomain\.com)$ [NC]
    RewriteRule ^([^-]*)-.*/?$ https://%1.%2.$1/ [NE,R=301,L]
    


    In case you want to only apply these rules to un-es urls then try following, make sure you either use above OR following rules at a time.

    RewriteEngine ON
    RewriteCond %{HTTP_HOST} ^(www|stage)\.(sitedomain\.com)$ [NC]
    RewriteRule ^(us)-en/?$ https://%1.%2.$1/ [NE,R=301,L]