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 the server is, configuration file
1. create the file with Password

First you will need a file to store the username/password (encrypted) using the 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

chmod 755/usr/local/bin/

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

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: hocvps2/public_html/.htpasswd

2. configure Nginx

Open the Nginx configuration file


Add the following content to the server {…}

server {
listen 80;
location ^ ~/test {
auth_basic “Restricted”;

Reload Nginx

/etc/init.d/nginx reload

Now when visiting 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.