Configure Password Authentication Nginx Server

Author: Al-mamun Sarkar Date: 2020-04-14 14:00:25

Configure Password Authentication Nginx Server. The following commands show how to create password authentication for the location of Nginx. 

 

Install apache2-utils module:

apt install apache2-utils -y

 

Create a username and password:

htpasswd -c /etc/nginx/passwords admin

Here user name is admin. Give a password.

 

Show File Permission:

ls -ltr /etc/nginx/passwords

 

Show file content:

cat /etc/nginx/passwords

 

Update file permission:

chown www-data /etc/nginx/passwords
chown 600 /etc/nginx/passwords

 

Update appointments location for adding password:

location /appointments/ {
        auth_basic "Authentication is required....";
        auth_basic_user_file /etc/nginx/passwords;

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
                fastcgi_intercept_errors on;
        }

        allow 192.168.33.0/24;
        allow 10.0.0.0/8;
        deny all;
}

artofcse.local.conf file will be as follows:

server {
        listen 80 default_server;
        server_name artofcse.local www.artofcse.local;
        index index.html index.htm index.php;
        root /var/www/artofcse.local;

        access_log /var/log/nginx/artofcse.local.access.log;
        error_log /var/log/nginx/artofcse.local.error.log;

        location / {
                try_files $uri $uri/ =404;
        }

        location /images {
                autoindex on;
                access_log /var/log/nginx/artofcse.local.images.access.log;
                error_log /var/log/nginx/artofcse.local.images.error.log;
        }

        location /appointments/ {
		        auth_basic "Authentication is required...."
		        auth_basic_user_file /etc/nginx/passwords

		        location ~ \.php$ {
		                include snippets/fastcgi-php.conf;
		                fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
		                fastcgi_intercept_errors on;
		        }

		        allow 192.168.33.0/24;
		        allow 10.0.0.0/8;
		        deny all;
		}

        location /deny/ {
                deny all;
        }

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
                fastcgi_intercept_errors on;
        }

        error_page 403 /403.html;
        location = /403.html {
                internal;
        }

        error_page 404 /404.html;
        location = /404.html {
                internal;
        }

}

 

 

Test Configuration:

nginx -t

 

Reload Nginx:

systemctl reload nginx

 

Now if you visit http://127.0.0.1/appointments/ It will ask for a user and password. Give created username and password to access the link.