Search code examples
azureapache.htaccessmod-rewriteapache-expression

.htaccess If/Else statement doesn't work with HTTP_HOST


This is my .htaccess file:

 RewriteEngine On

 <If "%{HTTP_HOST} == '<myHost>'">
   RewriteRule ^$ <url> [R=301,L]
 </If>
 <Else>
  RewriteRule ^$ <another_url> [R=301,L]
 </Else>

But it doesn't work and it seems like the <If> statement is ignored. I also made an echo from $_SERVER['HTTP_HOST'] in PHP and there I get the value I expected. Also, the RewriteRule is working if I remove the If/Else statement.

I'm using Azure Webapp with Apache/2.4.38 (Debian)


Solution

  • Inside if and else block you can use RedirectMatch directive as it works with it . RewriteRule doesn't work because it overrides and conflicts with IF/ELSE.

     RewriteEngine On
    
     <If "%{HTTP_HOST} == '<myHost>'">
     RedirectMatch 301 ^/$ https://example.com
     </If>
     <Else>
     RedirectMatch ^/$ https://example2.com
     </Else>