How to Whitelist Localhost in Apache


whitelist localhost in apache

When you website is under development or maintenance, you may need to deny access to all but whitelist localhost. So let us take a look at how to whitelist localhost in Apache.

 

How to Whitelist Localhost in Apache

Here are the steps to whitelist localhost in Apache.

Before proceeding, please ensure you have enabled .htaccess (mod_rewrite) in your Apache web server. Here are the steps to do it:

 

Place your .htaccess file in the root document folder of your website (/var/www/html)

 

1. Open .htaccess file

Open .htaccess file using a text editor. It is generally located at /var/www/html.


$ sudo vim /var/www/html/.htaccess

 

2. Whitelist Localhost

Let’s say all pages on your website/portal are password protected/restricted and you want to allow access to localhost. In that case, add the following Directory block to your .htaccess file.

Apache 2.2


<Directory /var/www/html>
Order allow,deny
Allow from 127.0.0.1
Allow from localhost
Allow from 192.168
Satisfy Any
</Directory> 

So your virtual host file will look something like


<VirtualHost *:80>
 ServerAdmin webmaster@localhost
 DocumentRoot /var/www/html
 <Directory /var/www/html>
    Order allow,deny
    Allow from 127.0.0.1
    Allow from localhost
    Allow from 192.168
    Satisfy Any
 </Directory>

 ErrorLog ${APACHE_LOG_DIR}/error.log
 CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

 

Apache 2.4+


<Directory /var/www/html>
  Require ip 127.0.0.1
  Require ip localhost
  Require ip 192.168
</Directory>

 

The above code will enable access to all to the specified directory.

 

If you want to allow access only to specific directory such as /downloads/

Apache 2.2


<Directory /downloads/>
Order allow,deny
Allow from 127.0.0.1
Allow from localhost
Allow from 192.168
Satisfy Any
</Directory> 

Apache 2.4+


<Directory /downloads/>
Require ip 127.0.0.1
Require ip localhost
Require ip 192.168
</Directory>

 

 

3. Restart Apache web server

Restart Apache web server to apply changes


$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]

 

That’s it! You can access your website or specific directories via localhost.

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!