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 block IPv6 IP addresses in .htaccess

How do Invokable Controllers work in Laravel?

How to view all installed PHP modules?

How to show (or log) all SQL queries executed by Laravel

How to set custom HTTP headers in Apache (by editing .htaccess)

How to review blog posts (written by other users) before they get published on your WordPress blog?

How to select what columns to return when calling ::all()

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

How to Extract Query String (from a URL) Into an Associative Array in PHP

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