Skip to content

Tutorial: .htaccess

Deny or Allow Users Based on IP Address
Occasionally you have the need to deny users from accessing your web site. Or, you have a private site that you want to only allow certain people to access. Sure, you can use passwords for allowing users, but what about a bad user? Apache makes it easy to block certain IP addresses, or only allow certain IP addresses to connect.

It is important to note that this requires that you know the IP address you want to allow or block. And, since most internet users connect through a dynamic IP address, just because you block someone now doesn’t mean that they stay blocked. You also can block a bunch of people by blocking a single IP. The school I work at connects out as the same IP address, so if you blocked me from your site you would also be blocking everyone else at the school.

The directives we are going to be using are allow from and deny from. Both take the IP address as an option. So:

deny from 127.0.0.1 denies access from the user with the IP 127.0.0.1. Not a good idea, by the way. 127.0.0.1 is the “loopback” address for the computer to connect to itself. But, you could use allow from 127.0.0.1 to only allow connections from that computer. I did this before I had a separate server on my home network to serve web projects.

One important note here: the server can be configured to either look at the allowed list or denied list first. So, if you allow someone without denying and the server is set up to look at allow first, you will not deny anybody. But, if the server is set up to deny first and you allow, then everyone else would be denied. Check with your host on this one.

You can also use allow from all or deny from all to allow or deny all connections.

But, you do not have to use the full IP address. If you use allow from 192.168.1 it will only allow connections from 192.168.1.0 to 192.168.1.254. This is how mine is set up on my development server. It only allows connections from inside my network. Of course, my firewall should take care of that too, but I’m pretty obsessive.

Pages: 1 2 3 4 5

Published inProgramming

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *