Access controls in Apache
There are various ways in which you can control access to a resource in Apache.
Here, we'll focus on managing access using a .htaccess file. Every virtual host on a machine has its own .htaccess file.
However, for the .htaccess file to have any effect regarding access control, the Apache server needs to have AllowOverride AuthConfig in the virtual host's configuration. For example, this can look like below:
<VirtualHost *:443>
ServerName my-test.site
ServerAdmin webmaster@my-test.site
DocumentRoot /var/www/my-test.site
<Directory /var/www/my-test.site>
Options Indexes FollowSymLinks
AllowOverride AuthConfig
Require all granted
</Directory>
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/my-test.site/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/my-test.site/privkey.pem
</VirtualHost>Once the AllowOverride directive is in place, you can start limiting access through a .htacess file.
Protecting a directory with a username and a password
First, create a password file:
Add the following to a .htaccess file in the virtual host's document root:
Now, when someone tries to access the files in this virtual host's document root, they'll be prompted to enter a username and password.
Combining a username with the directive "Satisfy any"
Something that isn’t as widely known is the Apache directive Satisfy any. If you add the following to the above .htaccess file:
...you change the behavior from requiring a password to requiring that the user either originates from 2a02:750:dead:beaf::/64 or provides a username.
With this setup, for example, a developer can access the website without entering a password (if they originate from 2a02:750:dead:beaf::/64), while the site remains inaccessible to regular users. If the developer wants to access the site from outside of 2a02:750:dead:beaf::/64 they can still do that using the username/password.
Blocking IP address
To only allow access from two specific IP addresses, edit the .htaccess file to only contain the content below:
We can also turn it around: block only those two IP addresses while allowing everything else. This example is, in other words, the complete opposite of the above example:
More information
There is additional information about the .htaccess file available on Apache's website: https://httpd.apache.org/docs/current/howto/htaccess.html
Last updated
Was this helpful?