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

How to split a string into an array, in JS

How to find the index of a value in an array in JS?

How to get table column names from a database table in Eloquent?

How to undelete a soft deleted Eloquent row?

What are the SPL data structures

How to block an IP range based on CIDR in Apache with .htaccess

What is YAGNI?

How to round a number in JS?

How to eager load multiple levels of relationships in Eloquent?

How to add the default charset to UTF-8 in .htaccess