How Nginx Add Basic Auth

Server Environment

1
2
3
4
$ cat /etc/issue
Ubuntu 14.04.4 LTS
$ nginx -v
nginx version: nginx/1.10.3 (Ubuntu)

Install Nginx

1
$ sudo apt-get install -y apache2-utils nginx
  • apache2-utils is a tool that generate a password file

Create A Nginx User Named “liyuliang”

1
2
$ sudo htpasswd -c /etc/nginx/.htpasswd liyuliang
New password:

Entry your password after this command

Add Auth Type In Your Nginx Config

1
$ sudo vim /etc/nginx/sites-enabled/default
1
2
3
4
5
6
7
8
9
10
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
# Uncomment to enable naxsi on this location
# include /etc/nginx/naxsi.rules

auth_basic "Private Property";
auth_basic_user_file /etc/nginx/.htpasswd;
}

Restart Nginx

1
$ sudo service nginx restart

Proxy Pass With Auth

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
server {
server_name _
listen 80;
client_max_body_size 100M;


location / {
proxy_pass http://127.0.0.1:3030;
proxy_set_header Host $host:80;
proxy_set_header X-Real-IP $remote_addr;

auth_basic "Private Property";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}

It must be passed to proxy before checking authorization

Share