.htaccess SetEnvIfNoCase Host exclude specific subdomain

Viewed 116

We got a bunch of domains for one vhost. All domains including any subdomains require a basic auth except we define them as "live". When defining a domain as "live" also all subdomains are live.

SetEnvIfNoCase Host ^(.*\.)?domain1\.tld$ live
SetEnvIfNoCase Host ^(.*\.)?domain2\.tld$ live

<RequireAny>
    Require valid-user
    Require env live
</RequireAny>

Now I want to exclude dev.domain1.tld , so that the basic auth is required again.

How do I need to change RegEx in order to exclude dev.domain1.tld ?

1 Answers

You can do as @AmitVerma suggested in comments and use a negative lookahead. Or, you can simply unset the live env var when that hostname is requested.

For example:

SetEnvIfNoCase Host ^([^.]+\.)?domain1\.tld$ live
SetEnvIfNoCase Host ^www\.domain1\.tld$ !live

The ! prefix on the env var in the second directive unsets the previously set live env var.

Just to note (.*\.) would match any number of sub-subdomains, in case that is an issue.

Would it be ^((?!dev\.|!test\.).*\.)?domain1\.tld$ then?

You should remove the second ! and you can remove the literal \. (literal dot) from the alternation. It is the ?! after the opening parenthesis that defines the negative lookahead (ie. the subpattern that should not occur). For example:

^((?!dev|test).*\.)?domain1\.tld$
Related