Apache .htaccess authorization with both IP check and password authentication

Have you ever been struggling to secure a website domain by both IP address whitelist and a password file? This means the user has to have a specific IP address to even be allowed, and after allowance the user must enter his/her password for access.

The solution to do this in a Apache .htaccess file is listed below.

Important things to notice are:

  • A password file is created using htpasswd in /home/domains/www.example.com/secure.passwd. This file can be located anywhere you like, as long as the user Apache runs as can read it
  • The line with Satisfy All is the key to the solution. If you want the user to only have to fulfill one of the two requirements (has whitelisted IP or enters password) set this to Satisfy Any.
AuthType Basic
AuthName "Secure site"
AuthUserFile /home/domains/www.example.com/secure.passwd
Require valid-user
Order deny,allow
Deny from all
#Repeat the line below for all allowed IP addresses.
Allow from 127.0.0.1
Satisfy All