用 Nginx 把内部服务暴露出去,是最常见的部署方式。这篇记一份我反复用、基本不用改的配置模板。
基本转发
upstream app_backend {
server 127.0.0.1:8800;
keepalive 32;
}
server {
listen 443 ssl http2;
server_name kb.example.com;
ssl_certificate /etc/nginx/cert/fullchain.pem;
ssl_certificate_key /etc/nginx/cert/privkey.pem;
client_max_body_size 20m;
proxy_read_timeout 120s;
location / {
proxy_pass http://app_backend;
proxy_http_version 1.1;
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;
proxy_set_header Connection "";
}
}
几个容易漏的点:
proxy_http_version 1.1+Connection ""才能复用长连接,默认 1.0 每次都新建连接,QPS 高时 TIME_WAIT 堆得很吓人X-Forwarded-Proto不传的话,后端以为是 http,生成的重定向地址会变成 http,跳来跳去client_max_body_size默认只有 1M,传图直接 413
加一层访问口令
内部工具不想公开,用 Basic Auth 最省事:
htpasswd -c /etc/nginx/conf/kb_htpasswd reader
auth_basic "restricted";
auth_basic_user_file /etc/nginx/conf/kb_htpasswd;
注意:Basic Auth 是明文传输凭据(虽然有 TLS 保护),只适合自己用。而且这段配置如果写在面板生成的 vhost 里,面板保存设置时可能覆盖掉——我遇到过两次,后来把它挪到独立的 conf.d 文件里才稳。
静态资源与缓存
location ~* \.(jpg|jpeg|png|gif|webp|css|js|woff2)$ {
proxy_pass http://app_backend;
expires 30d;
add_header Cache-Control "public, immutable";
}
证书续期
acme.sh 装 cert 时带上 reload 命令,续期后自动生效:
acme.sh --install-cert -d kb.example.com \
--key-file /etc/nginx/cert/privkey.pem \
--fullchain-file /etc/nginx/cert/fullchain.pem \
--reloadcmd "nginx -s reload"
验证是否装好:
acme.sh --list # 看 Next Renew 时间
systemctl list-timers | grep acme
排查顺序
502:后端没起来或端口不对,curl 127.0.0.1:8800 先确认。
504:超时,看 proxy_read_timeout 和后端处理时间。
404:proxy_pass 结尾有没有多余斜杠,这会改变路径拼接规则。
413:client_max_body_size。
这套配置我从 2020 年用到现在,除了换域名几乎没动过。
- THE END -
最后修改:2022年10月15日
非特殊说明,本博所有文章均为博主原创。
如若转载,请注明出处:https://mi-blog.cn/archives/663
共有 0 条评论