Sign in
Log inSign up
How To Set Up Password Authentication with Nginx in CentOS

How To Set Up Password Authentication with Nginx in CentOS

Ehsan Aghaei's photo
Ehsan Aghaei
·Jan 7, 2020

Hi, I'm going to show you how to put password protection on specific directory with Nginx. Thats simple and straight forward. you just need to create passwords file and tell Nginx to use that for authentication. so let's get through this.

1.Create Password file

firs we need to create a file which contains the usernames and corresponding passwords. we can create that file under

/etc/nginx/.htpasswd

then we are going to generate one username and password, there are so many tools that you can use for this purpose but, the simplest way is to use this online tools and generate you usernames and passwords.

.htpasswd Generator

then get your user and pwd and put into the generated .htpasswd file.

admin:$apr1$QDBt2IBU$W6ti5VWS4ddDVhG5seN2G0

remember you can have multiple users by putting each one in separate line.

2.Modify Nginx congifuration

Default Nginx configuration is available under this path in CentOS after installation.

/etc/nginx/nginx.conf

use vim or any other editor that you like and modify the configuration file like below.

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.html index.htm;

    server_name localhost;

    location / {
        try_files $uri $uri/ =404;
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
}

we only need to add two line under the location that we need to be password protected.

auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;

with these lines we are telling Nginx that this directory is password protected , we are addressing it to use the available username and password under the path specified file. Simply we are done, now by accessing you server you Nginx will ask you for authentication and you need to provider the username and password.

Cheers.