Apache 2.4 .htpasswd protection and whitelisting multiple IP addresses

A customer asked us to secure their development environment using .htaccess and .htpassword functionalities. They wanted the ability to browse the site from their own IP addresses without inputting a password. This is of course achievable with Apache's standard functionality, however when particularly complex .htaccess files are used, one may run in to issues with overlapping rules unless specific measures are taken.

Ordinarily we would use this standard .htaccess ruleset to achieve password protection with allow IP overrides:

AuthType Basic
AuthName "Development Environment"
AuthUserFile "/path/to/.htpasswd"
require valid-user
Order allow,deny
Allow from 192.168.30.40
satisfy any

The above is designed for Apache 2.2 and while it will still work on Apache 2.4 certain functionality is different and may cause problems. In particular, unless it is wrapped inside an <if> then one may experience problems. So, here is our proposed solution:

<If "%{REMOTE_ADDR} != '127.0.0.1'">
AuthType Basic
AuthName "Development Environment"
AuthUserFile /path/to/.htpasswd
require valid-user
require ip 192.168.30.40
require ip 10.0.0.101
require ip 172.17.1.120
</If>

With this solution, we are containing all of our code within an block which will not affect any of the .htaccess content above nor below. We are allowing the local host 127.0.0.1 full access as it probably should, and then using 'require ip' rules to allow additional addresses access.

  • 6 Users Found This Useful
Was this answer helpful?

Related Articles

Apache configuration for receiving reverse-proxied SSL traffic

Many customers use SSL-terminating reverse proxies and load balancers in front of their Apache...

cPanel: Resolve 'Forbidden' errors after removing mod_ruid2

So you have rebuilt Apache on your cPanel server to use suPHP instead of mod_ruid2... but you are...

Redirect http to https

Once you've got your SSL certificate installed, you'll want to switch your site traffic from http...

Optimise cPanel PHP-FPM performance

Activating a PHP-FPM pool for your cPanel domain will give a hefty performance boost over the...

Nginx-like "microcaching" using Apache mod_cache

Nginx is well known for its high performance 'microcache' feature, which is often used to make...