Nginx Location 配置
安装 htpasswd 工具
1
2
3
4
5# CentOS / RHEL
yum -y install httpd-tools
# Ubuntu / Debian
apt -y install apache2-utils生成密码文件
1
2
3
4
5
6
7
8# -c 创建文件,-b 直接在命令行指定密码
htpasswd -bc /etc/nginx/htpasswd admin YourPassword123
# 生成的文件内容类似于:
admin:$apr1$nk.CIrS7$eHHqORaeDBTVltMKsD6u/.
# 如果需要添加更多用户(不覆盖已有用户),去掉 -c 参数:
htpasswd -b /etc/nginx/htpasswd user2 Password456为 api 接口配置独立的日志文件,以及将该日志文件放到 Nginx 目录,开启目录列表,并配置仅允许该接口的日志文件可访问
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47...
# api 接口
location /api/ {
proxy_pass http://backend_api/;
# 代理头设置
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_set_header X-Forwarded-Proto $scheme;
# WebSocket 支持(如果后端需要)
proxy_http_version 1.1;
proxy_set_header Connection "";
# 超时设置
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 日志路径
access_log /var/log/nginx/api_access.log;
error_log /var/log/nginx/api_error.log;
}
# 日志访问
location /api_log/ {
alias /var/log/nginx/;
autoindex on; # 开启目录列表
autoindex_exact_size off; # 文件大小显示为 KB/MB
autoindex_localtime on; # 显示本地时间
# 开启 HTTP Basic Auth
auth_basic "Login Required";
auth_basic_user_file /etc/nginx/htpasswd;
# 仅允许访问以 api_开头的,以 .log 结尾的日志文件
if ($uri !~* ^/api_log/(api_[^/]+\.log)?$) {
return 403;
}
# 可选:限制只允许内网访问
allow 192.168.0.11/24;
deny all;
}
...
4 检查配置文件,重载配置文件
1 | nginx -t |
