nginx配置「锦上添花」的小修小补

奥黛丽·逐爱者
2026-01-08 / 0 评论 / 5 阅读 / 正在检测是否收录...

1. 统一 SSL 配置块(可维护性)

把重复的 ssl_* 指令抽成一个独立文件,主配置里 include 即可,例如:

# /etc/nginx/ssl/ssl_best.conf
ssl_certificate         /etc/nginx/ssl/_baidu.com.crt;
ssl_certificate_key     /etc/nginx/ssl/_baidu.com.key;
ssl_trusted_certificate /etc/nginx/ssl/_baidu.com.crt;
ssl_session_timeout     1d;
ssl_session_cache       shared:SSL:10m;
ssl_session_tickets     off;
ssl_protocols           TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers             ECDHE-ECDSA^...............:ECDHE-RSA-AE^.............-GCM-SHA384;

然后在每个 443 段里写一句:

include ssl_best.conf; 
配上路径,容器运行注意!
比如include /etc/nginx/ssl/ssl_best.conf;

以后换证书/调加密套件只改一行。

2. 补充安全响应头(看情况用吧)

新建 /etc/nginx/conf.d/security_headers.conf:

add_header X-Frame-Options           "SAMEORIGIN" always;
add_header X-Content-Type-Options    "nosniff" always;
add_header Referrer-Policy            "strict-origin-when-cross-origin" always;
# 如需上传或外链,按需调整 CSP
add_header Content-Security-Policy    "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

在 所有 443 段 的 location / 里加:

include security_headers.conf;
配上路径,容器运行注意!
比如include /etc/nginx/conf.d/security_headers.conf;

(Tomcat 已自带 X-Frame-Options,nginx 再统一一次无冲突。)

3. 代理头统一模板

把 proxy 头也抽成 /etc/nginx/conf.d/proxy_headers.conf:

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 REMOTE-HOST        $remote_addr;
proxy_http_version                  1.1;
proxy_set_header Upgrade            $http_upgrade;
proxy_set_header Connection         "upgrade";

以后 location / 里只要写:

proxy_pass http://backend_5800;
include proxy_headers.conf;
比如include /etc/nginx/conf.d/proxy_headers.conf;

Tomcat 路径同理。

4. 小优化:正则 location 加 break

location ~ ^/(test|oa|ob|oc) {
    proxy_pass http://tomcat;
    include proxy_headers.conf;
}

• 正则 ~ 会顺序匹配,保持放在「普通 location /」前面即可。
• 若担心性能,可改为:

location /oa { ... }
location /ob { ... }

5. 可选:Tomcat 真实 IP 日志

Tomcat 要记录访客真实 IP,在 server.xml 里加:

<Valve className="org.apache.catalina.valves.RemoteIpValve"
       remoteIpHeader="X-Forwarded-For"
       protocolHeader="X-Forwarded-Proto" />

nginx 已传头,直接可用。

附配置:

0

评论 (0)

取消