0

The user agent blocking code in my .htaccess file stopped working, though I didn't make any recent changes to it. To troubleshoot this I changed the user agent in FF and created a sub-directory with its own .htaccess file and one php file. In that file I added code to display the $_SERVER['USER_AGENT'] string. It shows the UA I am using and is:

    Mozilla/5.0 (compatible; Konqueror/4.2; Linux) KHTML/4.2.96 (like Gecko)

In my .htaccess file I have the following but when I visit that location I am not blocked.

    RewriteEngine On
    RewriteCond %{HTTP_USER_AGENT} "^Konqueror$" [NC]
    RewriteRule ^ - [F]

I added the following, with my real IP, after the above to verify the rewrite was working and it blocked me:

    RewriteCond %{REMOTE_ADDR} ^12\.23\.45\.666
    RewriteRule ^ - [F]

Does anyone know what the problem is?

user3052443
  • 758
  • 1
  • 7
  • 22

1 Answers1

1

This won't work due to the "^" at the start and the "$" at the end of your matching pattern in the RewriteCond. These two special characters anchor a regular expression to the beginning and the end of the subject, so the search string. So your condition will only match of the header contains the exact string "Konqueror" with nothing before or after that. That is not what you want.

The word "Konqueror" appears in the middle of that string you send as a user agent. So you want to match any string that contains the word "Konqueror" most likely. Just leave both special characters away and you are happy.

You can also remove the quote characters, they are not required.

So simply use that condition:

RewriteCond %{HTTP_USER_AGENT} Konqueror [NC]
arkascha
  • 41,620
  • 7
  • 58
  • 90
  • Thank you - that fixed it. I thought it was working before but I guess the UA I was trying to block just stopped for a while. Obviously your change works but I'm curious since I'm not that good with regex, why isn't it something like ^.*konqueror.*$ since the actual UA string contains more than the name? – user3052443 Oct 05 '22 at 17:39
  • 1
    `^.*konqueror.*$` and just `konqueror` are identical in their meaning as a regular expression. Just read slowly what your suggested expression matches: beginnin at the start of the subject match _any_ occurrences of any character, then the literal string "konqueror", then again _any_ occurrences of any character until the end of the subject. That obviously is redundant, just leave away the anchoring to the subjects start and end. Comes out the same. Just have a try yourself using a simply online regex tester like regex101. You need to get fluent in regexes anyway ;-) – arkascha Oct 05 '22 at 17:56