Access Apache only from localhost in Linux

When you install Apache you expose your computer on the internet allowing attackers to access your webserver. If you want to restrict the access to external requests you would setup few rules.

The easiest way is to write in the root of your webserver (usally located in /var/www/html/ ) a file called .htaccess that should contain the following lines:

Order deny,allow
Allow from
Deny from all 

The first row indicates the order of the rules evaluation, the second one says that the access from localhost is allowed and the third one denies all the other accesses.

This file will not be effective until you edit also the apache2.conf file, normally located at /etc/apache2/apache2.conf

In this file you have to find the following line:

<Directory /var/www/>
     Options Indexes FollowSymLinks
     AllowOverride None
     Require all granted

and change to:

<Directory /var/www/>
     Options Indexes FollowSymLinks
     AllowOverride All
     Require all granted

Remember then to restart (or reload) Apache running:

$ sudo systemctl restart apache2

To check if everything is ok you can access the webserver from your public ip getting the “403 Forbidden” response.

Remember that you can access from browser to ipv6 addresses enclosing the ip in square brackets like “[2001 : …. ]”

You can also enable or disable errors adding the following lines in .htaccess :

php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag  log_errors on
php_value error_log  /var/www/errors.log


This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.