Nginx 配置避坑指南:10 个生产环境常见错误

Nginx Configuration Pitfalls — 10 Common Production Mistakes

| iDev Team | 2026-08-13T09:46:23

反向代理不生效、静态文件 404、CORS 报错、SSL 配置不当……这些 Nginx 配置问题你踩过几个?

Reverse proxy not working, static file 404s, CORS errors, SSL misconfiguration... How many of these Nginx pitfalls have you hit?

1. location 优先级搞混Nginx 的 location 匹配有优先级:精确匹配(=) > 前缀优先(^~) > 正则(~) > 普通前缀。最常见的坑:你的 API 反代用了普通 location,但图片缓存用了正则 location,结果 API 返回的图片被正则拦截了。解决:API 反代加 ^~ 前缀。2. proxy_pass 末尾斜杠proxy_pass http://127.0.0.1:8080 和 proxy_pass http://127.0.0.1:8080/ 行为完全不同。不带斜杠会保留原始 URI,带斜杠会去掉 location 匹配的前缀。这个差异导致无数调试噩梦。3. CORS 只配了 OPTIONSCORS 预检请求(OPTIONS)通过了,但实际请求(GET/POST)没有返回 CORS 头。原因:你的 CORS 配置放在了拦截 OPTIONS 的 location 里,但实际请求走了另一个 location。4. client_max_body_size 忘了加默认 1MB。上传超过 1MB 的文件直接 413 报错,但报错信息不明显,经常被误判为后端 bug。5. SSL 没有强制 HTTPS配了 SSL 但没有 HTTP → HTTPS 跳转,用户通过 HTTP 访问时走的是明文,SSL 白配了。更多常见问题6. gzip 没有开启:传输体积大一倍7. 缓存头没有配:静态文件每次都重新下载8. 日志文件撑爆磁盘:没有配 logrotate9. upstream 没有健康检查:后端挂了还在转发10. 修改配置后忘了 reload:改了不生效,怀疑人生


1. Location Priority ConfusionNginx location matching has priorities: exact(=) > prefix priority(^~) > regex(~) > plain prefix. Common trap: your API proxy uses plain location, but image caching uses regex — API-served images get intercepted by the regex rule. Fix: add ^~ to the API proxy location.2. Trailing Slash in proxy_passproxy_pass http://127.0.0.1:8080 vs proxy_pass http://127.0.0.1:8080/ behave completely differently. Without slash: preserves original URI. With slash: strips the location prefix. This subtle difference causes countless debugging nightmares.3. CORS Only Configured for OPTIONSCORS preflight (OPTIONS) passes, but actual requests (GET/POST) lack CORS headers. Cause: CORS config is in the OPTIONS-handling location, but actual requests hit a different location block.4. Missing client_max_body_sizeDefault is 1MB. Uploading files over 1MB returns 413, but the error isn't obvious — often misdiagnosed as a backend bug.5. SSL Without Forced HTTPSSSL is configured but HTTP→HTTPS redirect is missing. Users accessing via HTTP transmit in plaintext — SSL is wasted.More Common Issues6. gzip not enabled: double the transfer size7. Missing cache headers: static files re-downloaded every time8. Log files filling disk: no logrotate configured9. No upstream health checks: forwarding to dead backends10. Forgot to reload after changes: edits don't take effect

← Back to News