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)
2
Answers
Inside
if
andelse
block you can useRedirectMatch
directive as it works with it . RewriteRule doesn’t work because it overrides and conflicts with IF/ELSE.The
<If>
statement is not ignored. The "problem" is that when used inside an<If>
expression theRewriteRule
pattern matches the absolute filesystem path, not the requested URL-path that you are expecting.The
<If>
block changes the order of processing.<If>
blocks are merged very late, after.htaccess
files are ordinarily processed and seemingly after the request has been remapped back to the filesystem (ie. after the directory-prefix has been added back).With this in mind, you could change your rules to the following to get this to work:
Where
/file/path/to/document-root/
is the absolute filesystem path to your document root directory (where the URL-path/
maps to).Alternatively, check the URL-path using the
REQUEST_URI
server variable in a condition instead. For example:Or, check the
REQUEST_URI
var in the<If>
(and<ElseIf>
) expression(s). On Apache 2.4.26+ you can nest expressions. For example:Or, use a mod_alias
RedirectMatch
directive inside the<If>
expression, as suggested in @AmitVerma’s answer. The mod_aliasRedirectMatch
(andRedirect
) directives always reference the requested (root-relative) URL-path, regardless of context, so you don’t get this ambiguity as with mod_rewrite.Or, just use mod_rewrite, there is no need for the
<If>
/<Else>
expression here. for example: