需求场景

nignx转发的服务想要开启basic auth认证,后端某些不需要认证的页面不太想被人访问,所以先要通过basic auth认证,才能通过登录界面登录到系统中,可以减少一些潜在的攻击吧。

但很多路由需要后端验证,需要这些路有要写到nginx中,希望匹配到这些路有走后端服务的验证,而不走basic auth认证

htpasswd安装

centos

1
yum install -y httpd-tools

ubuntu

1
apt-get install apache2-utils

配置BASIC_AUTH

生成用户名密码

1
htpasswd -c -d /etc/nginx/passwd.d/admin_passwd  admin

nginx.conf完整配置示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
server {
listen 8200;
client_max_body_size 500M;
# 统一开启认证
auth_basic "login";
auth_basic_user_file /etc/nginx/passwd.d/admin_passwd;
# 正则匹配关键字为api和static
location ~ /.*[api|static]/ {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://xxxxx;
auth_basic off; #将认证关掉,采用flask后端认证
}
location / {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://xxx;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}

根据url正则进行匹配,除api,static路由都进行basic_auth认证,再增加 location ~ /.[api|static]/这里增加到[]里即可 location ~ /.[api|static|xxxx]/