Search code examples
apache.htaccessapache2.4

.htaccess - if statement: host contains (not equals) subdomain


I have these statements in my .htaccess, to match subdomains:

<If "req('Host') == 'subdomain.domain.com'"></If>
<If "req('Host') == 'subdomain.staging.domain.com'"></If>

How can I write these statements so that subdomains of these subdomains will also match:

s1.subdomain.domain.com
s1.subdomain.staging.domain.com

Something like this:

<If "req('Host') contains 'subdomain.domain.com'"></If>
<If "req('Host') contains 'subdomain.staging.domain.com'"></If>

Solution

  • You are looking for "regular expressions".

    Your above examples would be converted into:

    <If "req('Host') =~ /^(?:s1\.)?subdomain\.domain\.com$/">
    <If "req('Host') =~ /^(?:s1\.)?subdomain\.staging\.domain\.com$/">
    

    The more general version to accept any "subdomain" would be something like that:

    <If "req('Host') =~ /^(?:.+\.)*subdomain\.domain\.com$/">
    <If "req('Host') =~ /^(?:.+\.)*subdomain\.staging\.domain\.com$/">