There may be some instances when you should use htaccess to block an IP address or even a range of IP addresses. For instance, your website may be receiving a lot of bot or spam traffic from certain IPs, or you just want to filter certain visitors. There are several ways this can be done through a .htaccess file depending on what your goal is. Below are several different sceneries and examples of .htaccess syntax that can be added to a blank .htaccess file or to the top of your existing .htaccess file.
Restrict Access From a Single IP
You can easily restrict access to a single IP address while allowing traffic from all other sources. To do this replace ‘192.168.1.1’ with the desired IP address you wish to block.
Deny from 192.168.1.1
Allow from all
Restrict Access From a Range of IPs
To restrict a range of IP addresses the process is very similar except you can leave off a set of digits to act as a wild card. In the below example the fourth set of digits has been left. Therefore, this will block any IP with a fourth set of digits such as ‘192.168.1.1’ & ‘192.168.1.255’ but will allow all other traffic. Replace the example IP address range in the example below with the range you wish to block.
Deny from 192.168.1.
Allow from all
Restrict Access from All IPs Except Yours
You may want to restrict all website access except from your own IP address. Below is the an example of how to accomplish this. Replace ‘192.168.1.1’ with your IP address that you want to allow access and all other requests will be blocked.
Deny from all
Allow from 192.168.1.1
The .htaccess file perimeters above are very flexible and you can combine multiple Deny and Allow as necessary if you have specific IPs or ranges you wish to allow or disallow. Typically when using the above rules to block an IP address the web server would respond with 403 Forbidden which means the sever understood the request but is refusing to authorize it.
Mike is the managing member at MSLtek and is an avid web consultant and web developer. He enjoys solving complex problems and building awesome stuff.