Get your server issues fixed by our experts for a price starting at just 25 USD/Hour. Click here to register and open a ticket with us now!

Author Topic: Setting up Nginx Basic HTTP Authentication  (Read 2778 times)

0 Members and 1 Guest are viewing this topic.

sajugovind

  • Guest
Setting up Nginx Basic HTTP Authentication
« on: August 10, 2014, 08:14:16 pm »
There are times that you want certain directories to be accessible only to authorized users hence you want to setup restrictions on http server level using basic authentication. This tutorial will exactly tells you how to do just that on Nginx http server. If you are running Nginx for multiple websites then you must have an individual configuration file per domain website that you are serving.

Generate user file to be used for basic authentication. This is where user credentials are lookup during authentication.

Using openssl, you can generate the password that is compatible for both Nginx and Apache http servers.

Code: [Select]
openssl passwd your_password
Example content of your password file should be like this:

Code: [Select]
seoroot:TtZtElTuqmeQ2
Now that you have your password file created, it is time to enable Nginx basic authentication by editing your Nginx website configuration file and insert the following directives.

Nginx Directives

Code: [Select]
location /path_to_your_restricted_directory/ {

        auth_basic "Restricted";

        auth_basic_user_file /path_your_htpasswd_file;

 }

Example Nginx Directives Configuration

Code: [Select]
location /webstats/ {

        auth_basic "Restricted";

        auth_basic_user_file /etc/nginx/mysite-htpasswd;
 
}

When you are done editing your Nginx website configuration file, you will need to restart your Nginx http process.

Code: [Select]
sudo service nginx restart
Once you have the web server restarted, and when you access the restricted directory, you will be prompted with a username and password. That’s about it, you have successfully setup Nginx basic authentication to protect the restricted area of your website.