How should I use the <If> directive in .htaccess?

Solution 1:

The <If> directive is only available in Apache 2.4+ and not 2.2 or earlier.

http://httpd.apache.org/docs/2.4/mod/core.html#if

Documentation not present in 2.2:

http://httpd.apache.org/docs/2.2/mod/core.html#if

Solution 2:

<If> is only available in Apache 2.4+, so firstly make sure that you have that version.

Examples

# Compare the host name to example.com and redirect to www.example.com if it matches
<If "%{HTTP_HOST} == 'example.com'">
  Redirect permanent "/" "http://www.example.com/"
</If>

<If "%{HTTP_HOST} =~ /regex/">
  SecFilterEngine Off
  SecFilterScanPOST Off
</If>

<If "%{REQUEST_URI} =~ m#/regex/including/slashes/#">
  SecFilterEngine Off
  SecFilterScanPOST Off
</If>

Alternatives to <If>

There are a few other solutions for doing conditional statements in Apache 2.2 if you're still stuck with that.

  • You can set environment variables via:

    • Apache configuration
    • SetEnvIf
    • mod_rewrite's RewriteMatch
  • Then you can perform conditional statements using

    <IfDefine MyEnvironmentVar>
       ...
    </IfDefine>
    

Example:

# Set environment variable if we're on staging site
SetEnvIf Host staging ROBOTS_NOINDEX

# Set environment variable if we're within a specific folder
SetEnvIf Request_URI ^/app/webroot/files/ ROBOTS_NOINDEX

# Send custom header if environment variable is set
Header set X-Robots-Tag "noindex" ENV=ROBOTS_NOINDEX