Created
November 25, 2014 13:55
-
-
Save artmouse/94c175835f829b07f54f to your computer and use it in GitHub Desktop.
How To Set Up HTTP Authentication With Nginx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Step 1: Apache Utils | |
We need htpasswd to create and generate an encrypted for the user using Basic Authentication. Install apache2-utils using the command below. | |
sudo apt-get install apache2-utils | |
Step 2: Create User and Password | |
Create a .htpasswd file under your website directory being served by nginx. The following command would create the file and also add the user and an encrypted password to it. | |
sudo htpasswd -c /etc/nginx/.htpasswd exampleuser | |
The tool will prompt you for a password. | |
New password: | |
Re-type new password: | |
Adding password for user exampleuser | |
The structure of the htpasswd file would be like this: | |
login:password | |
Note that this htpasswd should be accessible by the user-account that is running Nginx. | |
Step 3: Update Nginx configuration | |
Your nginx configuration file for the website should be under /etc/nginx/sites-available/. Add the two entries below under for the domain path that you want to secure. | |
auth_basic "Restricted"; | |
auth_basic_user_file /etc/nginx/.htpasswd; | |
The second line is the location of the htpasswd file for your website. | |
For example, lets say our nginx configuration file is /etc/nginx/sites-available/website_nginx.conf, open the file using vi or any editor of your choice. | |
sudo vi /etc/nginx/sites-available/website_nginx.conf | |
Then add the two lines into the following path: | |
server { | |
listen portnumber; | |
server_name ip_address; | |
location / { | |
root /var/www/mywebsite.com; | |
index index.html index.htm; | |
auth_basic "Restricted"; #For Basic Auth | |
auth_basic_user_file /etc/nginx/.htpasswd; #For Basic Auth | |
} | |
} | |
Step 4: Reload Nginx | |
To reflect the changes on our website reload the nginx configuration and try to access the domain that has been secured using Basic Authentication. | |
$ sudo /etc/init.d/nginx reload | |
* Reloading nginx configuration... | |
Now try to access your website or the domain path that you have secured and you will notice a browser prompt that asks you to enter the login and password. Enter the details that you used while creating the .htpasswd file. The prompt does not allow you to access the website till you enter the right credentials. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment