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 are generators in PHP, and how do they compare to arrays?

How to prevent Eloquent from adding created_at or updated_at timestamps?

How to generate an array for a dropdown (with ['key' => 'value']) suitable for a dropdown, from a Laravel collection of Eloquent objects?

How to output (echo/print) content in PHP

How to find out what version of Laravel you are using?

How to check if a object has a static variable defined?

How to add and remove items to an array in JS?

How to force gzip compression in Apache with .htaccess

What is the difference between var, let and const in Javascript?

What are route patterns in Laravel?