Simplyfing rule to ban by IP mask in .htaccess

Viewed 53

On my website I'm using this code in .htaccess, to ban some addresses:

RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^159\.138
RewriteRule .* - [F,L]

RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^114\.119\.1
RewriteRule .* - [F,L]

RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^185\.191\.171
RewriteRule .* - [F,L]

I've tried to write it as:

RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^159\.138
RewriteCond %{REMOTE_ADDR} ^114\.119\.1
RewriteCond %{REMOTE_ADDR} ^185\.191\.171
RewriteRule .* - [F,L]

But this crashes, and doesn't work. How can I merge those rules, so I don't need to write 3 lines for every IP ?

1 Answers

1st solution: with-in single shot to check all IPs together try following. Online demo of regex is: Online demo of tested regex

RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^((159\.138)|(114\.119\.1)|(185\.191\.171))$
RewriteRule ^ - [F,L]


2nd solution(conventional method): Could you please try changing your Rules to following once, based on your shown samples only. Please make sure to clear your browser cache before testing your URLs.

RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^159\.138 [OR]
RewriteCond %{REMOTE_ADDR} ^114\.119\.1 [OR]
RewriteCond %{REMOTE_ADDR} ^185\.191\.171
RewriteRule ^ - [F,L]

NOTE: Make sure either you use either of the rules at a time only.

Related