How to Configure Apache to Require Authorization to a Certain Directory Via an ".htpasswd" File Only When Requests Are Made From Outside the Local Area Network

Solution Verified - Updated -

Environment

Red Hat Enterprise Linux

Issue

Apache needs to be configured in such a way that requires authorization via .htpassword when requests are made from outside the local area network, while not requiring authorization from requests made from within the local area network.

Resolution

Please note that all commands will need to be run as the root user. First, an ".htpasswd" file will need to be created. This file will house the authorized user and password information for Apache.

# htpasswd -c .htpasswd user

In the above command, replace user with the username that Apache should use for external authorization. After running this command, a prompt to create a password will appear. This password will be used in conjunction with the username to gain external authorization from Apache.

Now a file named .htpasswdwill be located in the current working directory. This file should be moved to a new location under the Apache directory, which will be used to house .htpasswdfiles:

# mkdir -p /etc/httpd/htpasswd && mv .htpasswd /etc/httpd/htpasswd/

For this example, a previously created directory called secret, located inside the /var/www/html directory will serve as the directory to protect. Further, this example will use a local area network of 192.168.0.x with a subnet mask of 255.255.255.0. Using any text editor, the following directives must be added to to /etc/httpd/conf/httpd.conf:

<Directory /var/www/html/secret>     
     AuthType Basic     
     AuthName "Authorized Personnel Only"     
     AuthUserFile /etc/httpd/htpasswd/.htpasswd     
     Order allow,deny     
     Require valid-user            
     Allow from 192.168.0.0/24     
     Satisfy Any
</Directory>

After saving the changes to /etc/httpd/conf/httpd.conf, restart Apache:

# /sbin/service httpd restart

After restarting Apache,  a properly configured directory requiring authorization from users requesting access from outside of the local area network will now exist.

This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.