How to block IP addresses in Apache by using regular expressions (regex) in .htaccess

October 26, 2018

You can use regex in your .htaccess rules. You have to utilize a Rewrite Rule (so make sure you have the rewrite engine turned on) to do this block.

<IfModule mod_rewrite.c>
    RewriteCond %{REMOTE_ADDR} ^123.111.222.(1[0-9]|3[3-6]|9[0-9]$ [OR]
    RewriteCond %{REMOTE_ADDR} ^123.222.111.1([0-2][0-9])$
    RewriteRule .* - [F]
<\/IfModule>

Don't forget that you will probably need to enable the rewrite engine for these rules to work. Click the button below to find out how to do this.