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

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

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.

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

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


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

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Apache language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

What is the max size, by default, of GET variables?

How to disable file hotlinking in Apache with .htaccess

How to enable the rewrite engine in .htaccess?

PHP Date commonly used formats

How to make multiple routes share the same URL structure or URL parameters

How to set the timezone to UTC in .htaccess

What are generators in PHP, and how do they compare to arrays?

What are the SPL data structures

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

How to get the first row that matches some where queries, or create it if it doesn't exist (in Laravel's Eloquent)?