Restricting Access with HTTP Basic Authentication in Apache and Nginx

You can restrict access to your website or some parts of it by implementing a username/password authentication. Usernames and passwords are taken from a file created and populated by a password file creation tool, for example, apache2-utils.

Creating a Password File

sudo htpasswd -c /etc/httpd/.htpasswd admin
or
sudo htpasswd -c /etc/nginx/.htpasswd admin

Create additional user-password pairs. Omit the -c flag because the file already exists

Nginx configuration

server {
    ...
    auth_basic           "Administrator’s Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
location /public/ {
    auth_basic off;
}

}

Apache/httpd basic configuration

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
&lt;Directory "/var/www/html"&gt;
    AuthType Basic
    AuthName "Restricted Content"
    AuthUserFile /etc/httpd/.htpasswd
    Require valid-user
&lt;/Directory&gt;

</VirtualHost>

Apache/httpd with proxypass

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ProxyPass / http://localhost:990/
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
&lt;Location /&gt;
    AuthType Basic
    AuthName "Restricted Content"
    AuthUserFile /etc/httpd/.htpasswd
    Require valid-user
&lt;/Location&gt;

</VirtualHost>