.htaccess rewriterule if/else

.htaccessmod-rewrite

I have the following .htaccess code:

RewriteEngine on

<if "%{HTTP_HOST} =~ /^helpdesk\./">
    RewriteRule ^/?$ /index.php?pages=helpdesk&file=index [NC,L,QSA]
</if>

<if "%{HTTP_HOST} =~ /^account\./">
    RewriteRule ^/?$ /index.php?pages=account&file=index [NC,L,QSA]
</if>

Obviously, this is not working.

What I want to achieve:

when I go to http://helpdesk.domain.com, the index.php file must get the parameters pages=helpdesk and file=index. When I go to http://account.domain.com the index.php file must get the parameters pages=account and file=index.

When I replace the RewriteRule with a redirect, it works, but is this possible to achieve?

Thanks in advance!

Edit:

asked my question way to fast. This works.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^helpdesk\..* [NC]
RewriteRule ^/?$ /index.php?pages=helpdesk&file=index [NC,L,QSA]
RewriteCond %{HTTP_HOST} ^account\..* [NC]
RewriteRule ^/?$ /index.php?pages=account&file=index [NC,L,QSA]

But is this the correct way or is there a (better) alternative?

Best Answer

What you are trying to achieve is possible with both, and your currently working configuration is the traditional way of doing this. That's why there's plenty of examples for doing this with RewriteCond. The Expressions and directives If, ElseIf, Else and were introduced in Apache 2.4 as a long-awaited feature, and one of the first examples is to make rewriting more readable and predictable:

Some of the things you might use this directive for, you've been using mod_rewrite for up until now, so one of the side-effects of this directive is that we can reduce our reliance on mod_rewrite's complex syntax for common situations. Over the coming months, more examples will be added to the documentation, and we'll have a recipe section with many of the same sorts of scenarios that are in the mod_rewrite recipe section.

In fact, most of the commonest uses of mod_rewrite can now be replaced with the If directive, making them easier to read, and, therefore, less prone to error, and the redirect looping that so often plagues RewriteRule-based solutions.

Without testing, I'd say that using regular expressions with your use case makes this overly complicated. Because you are comparing Host: headers probably within a fixed domain, say example.com, you could use simple == (string equality) comparison operator instead of =~ (string matches the regular expression):

<ifModule mod_rewrite.c>
    RewriteEngine on
    <If "%{HTTP_HOST} == 'helpdesk.example.com'">
        RewriteRule ^/?$ /index.php?pages=helpdesk&file=index [NC,L,QSA]
    </If>
    <If "%{HTTP_HOST} == 'account.example.com'">
        RewriteRule ^/?$ /index.php?pages=account&file=index [NC,L,QSA]
    </If>
</ifModule>
Related Topic