skip to Main Content

I’m trying to set environment variables in my .htaccess file based on the top level domain of the server. But after there is a match for the condition, the .htaccess file does not execute further.

If there is no domain matched,_rooturl_ is set but _rootfolder_ is not. However, when a domain is matched _rootfolder_ is set but _rooturl_ is not. This also applies to any other redirects defined after that.

(...)

<If "req('Host') =~ /domain.com/ || req('Host') =~ /localhost/">
    RewriteRule .* - [E=_rootfolder_:www.domain.com]
</If>

<If "req('Host') =~ /domain.de/">
    RewriteRule .* - [E=_rootfolder_:www.domain.de]
</If>

RewriteRule .* - [E=_rooturl_:domainname]

(...)

TL;DR, I want my code to execute after passing the IF conditions.

2

Answers


  1. You may try this block of rules totally based on mod_rewrite rules:

    RewriteEngine On
    
    RewriteCond %{HTTP_HOST} (localhost|domain.com) [NC]
    RewriteRule ^ - [E=_rootfolder_:www.domain.com]
    
    RewriteCond %{HTTP_HOST} domain.de [NC]
    RewriteRule ^ - [E=_rootfolder_:www.domain.de]
    
    RewriteRule ^ - [E=_rooturl_:domainname]
    
    Login or Signup to reply.
  2. You can also do this with mod_setenvif:

    SetEnvIf Host "(localhost|domain.com)" _rootfolder_=www.domain.com
    SetEnvIf Host "domain.de" _rootfolder_=www.domain.de
    SetEnvIf Host ^ _rooturl_=domainname
    

    But after there is a match for the condition, the .htaccess file does not execute further.

    Although that shouldn’t happen with the directives you posted. It should "work" as intended. But this may depend on what other directives you have that depend on these env vars. And to some extent precisely what expressions and directives you are using.

    There are a few potential issues here:

    • <If> containers change the order of processing. The contents of <If> blocks are generally merged very late, however, mod_rewrite directives are still processed before mod_rewrite directives in the same context, regardless of where the <If> container(s) appear in the order of directives.

    • Unless you enable mod_rewrite inheritance (eg. RewriteOptions Inherit), the mod_rewrite directives in later <If> blocks completely override mod_rewrite directives in earlier <If> blocks. (In the same way mod_rewrite directives in a subdirectory .htaccess file completely override mod_rewrite directives in a parent .htaccess file.) This is OK if the <If> expressions are mutually exclusive or you expect later directives to override (and not add to) earlier directives.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search