Setup basic authentication in Nginx

February 18, 2017
Ubuntu Nginx

I use basic authentication for my websites in staging environments to restrict users from access the site. These are the steps for Nginx.

Install htpasswd to generate password hash:

sudo apt-get install apache2-utils

Generate the file with username user

sudo htpasswd -c /etc/nginx/.htpasswd user

Edit the config and add line 6 and 7.

sudo vi /etc/nginx/sites-available/
server {
    listen 80;
    location / {
        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/.htpasswd;
        proxy_pass http://localhost:5002;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;

Reload configuration files

sudo /etc/init.d/nginx reload