要隐藏特定主机下敏感响应头,需在对应server的location块中同时配置server_tokens off、proxy_hide_header和proxy_set_header Server "",并用curl -I验证各场景响应头是否清除。

要隐藏特定主机(即某个 server 块)下的特定敏感响应头,核心是把 proxy_hide_header 放在该 server 内的 location 中,并配合 server_tokens off 和 proxy_set_header Server "" 形成闭环。不能只靠一条指令,也不能写在错误位置。
确认目标主机与敏感头
先明确你要保护的是哪个 server 块(比如监听 example.com 的 443 端口),再用 curl -I https://example.com/api/test 查看实际返回的响应头,找出需隐藏的具体字段,例如:
-
Server: Apache/2.4.52(后端真实服务) X-Powered-By: PHP/8.1.27X-Application-Context: application:prod-
X-Minio-Deployment-Id: xxxxx...(若反代 MinIO)
在对应 server 的 location 中配置 proxy_hide_header
该指令必须写在启用代理的 location 块内,且必须位于 proxy_pass 之后。每个头单独一行,大小写不敏感但建议按标准格式书写:
server {
listen 443 ssl;
server_name example.com;
<pre class="brush:php;toolbar:false;"># 关闭 Nginx 自身版本标识(全局生效,推荐放 http 块,但放这里也有效)
server_tokens off;
location /api/ {
proxy_pass https://backend-api;
proxy_hide_header Server;
proxy_hide_header X-Powered-By;
proxy_hide_header X-Application-Context;
proxy_hide_header X-Minio-Deployment-Id;
}
location /static/ {
proxy_pass https://minio-backend/;
proxy_hide_header X-Amz-Request-Id;
proxy_hide_header X-Minio-Deployment-Id;
proxy_hide_header Server;
}}
彻底清除 Server 头的三要素缺一不可
仅写 proxy_hide_header Server 很容易失效,因为 Nginx 对 Server 头有特殊处理逻辑。必须同时满足:
-
server_tokens off;—— 阻止 Nginx 自己输出带版本号的Server头 -
proxy_hide_header Server;—— 屏蔽后端透传过来的Server值 -
proxy_set_header Server "";—— 强制清空该字段(覆盖可能残留的值)
这三项需共存于同一 location 块中,顺序无关,但都得有。
验证是否真正生效
重载配置后,分场景检查:
- 正常请求:
curl -kI https://example.com/api/users—— 确认无目标头 - 触发错误:
curl -kI https://example.com/404-test—— 错误页也必须不含Server或X-*敏感字段 - 对比前后:
curl -I http://localhost:8080(直连后端) vscurl -I https://example.com(走 Nginx)
注意:浏览器开发者工具可能缓存预检响应,务必以 curl -I 输出为准。











