Search code examples
apache.htaccessuser-agent

Limiting Specific User Agent to Internet Explorer via Apache?


I am trying to limit my site to only allow User Agents with the following to be able to hit my site:

Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko

Currently in my .htaccess file (/var/www/html/) I have the following:

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} !Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko [NC]
RewriteRule ^ - [F,L]

Solution

  • Ordinarily, the CondPattern (2nd argument to the RewriteCond directive) is a regular expression. So, you would need to convert this to a regex - notably, you would need to backslash-escape the literal dots and spaces. However, it would be easier to use the lexicographical equality operator instead, ie. = prefix. This then matches a literal string, not a regex.

    The spaces in the user-agent string are a special case since the space is an argument separator in Apache config files. These either need to be backslash escaped (or use the \s shorthand character class if using a regex), or enclose the whole argument in double quotes.

    Try the following instead:

    RewriteCond %{HTTP_USER_AGENT} "!=Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
    RewriteRule ^ - [F]
    

    The L flag is not required with the F flag - it is implied. If you specifically only want to allow that one user-agent then you don't need the NC flag on the condition.