Protect folders in Nginx

When using Apache, usually to protect the directory we often use .htaccess and htpasswd files… However, Nginx does not support htaccess. You take a look the HTTP Basic Authentication tutorial below to make protected directories in Nginx.

The goal

Protect the directory http://example.com/test/with the server is example.com/home//public_html/test/, example.com.conf/etc/nginx/conf.d/Nginx configuration file
1. create the file with Password

First you will need a file to store the username/password (encrypted) using the http://trac.edgewall.org/browser/trunk/contrib/htpasswd.py Python script. In addition, Apache’s can use htpasswd Tool however is set to add to the server should not discourage use.

Download the script on/usr/local/bin and run

cd/usr/local/bin
wget http://trac.edgewall.org/export/10791/trunk/contrib/htpasswd.py
chmod 755/usr/local/bin/htpasswd.py

Now you will create the file with password/public_html/.htpasswd hocvps/home/user, password example.com with hocvpstest. Note You can use any file and save in any place.

htpasswd.py-c-b hocvpstest hocvps/home//public_html/.htpasswd example.com

The parameter-c to create a new file if it is not there, if the file already exists, overwrite will therefore lose the user in advance. In case you want to add more user again, then quit the parameter-c goes:

htpasswd.py/home/hocvpstest2 hocvps2/public_html/.htpasswd b-example.com

2. configure Nginx

Open the Nginx configuration file

nano/etc/nginx/conf.d/example.com.conf

Add the following content to the server {…}

server {
listen 80;
[…]
location ^ ~/test {
auth_basic “Restricted”;
auth_basic_user_file example.com/home//public_html/.htpasswd;
}
[…]
}

Reload Nginx

/etc/init.d/nginx reload

Now when visiting http://example.com/test will have the message asking you to log out:

Basic HTTP Authentication

If you do not sign in or Login incorrect error message:

Basic HTTP Authentication Error

It is ok now.

Leave a Reply

Your email address will not be published.