如何在Flask+Gunicorn+Nginx的所有端点隐藏Server响应头?
彻底隐藏Flask+Gunicorn+Nginx应用的Server响应头
1. 全局配置Gunicorn,移除所有请求的Server头
在gunicorn.conf.py中添加以下配置,确保Gunicorn不会给任何响应添加Server头(包括Worker进程初始化后的重置情况):
import gunicorn # 覆盖Gunicorn默认的Server标识 gunicorn.SERVER = '' # 防止Worker进程启动时重置Server配置 def post_fork(server, worker): gunicorn.SERVER = ''
启动Gunicorn时必须指定该配置文件:
gunicorn -c gunicorn.conf.py your_flask_app:app
2. 配置Nginx,禁止自身输出并隐藏后端Server头
修改Nginx配置文件(主配置nginx.conf或站点专属配置):
2.1 关闭Nginx自身的Server标识
在http块中添加:
server_tokens off;
这会阻止Nginx在响应头中输出自身的版本信息。
2.2 强制隐藏后端传递的Server头
在代理Gunicorn请求的location块中,替换之前的proxy_pass_header Server,改为:
location / { proxy_pass http://127.0.0.1:8000; # 替换为你的Gunicorn上游地址 # 隐藏后端返回的Server头 proxy_hide_header Server; # 可选:同时隐藏Flask默认的X-Powered-By头 proxy_hide_header X-Powered-By; }
3. 检查Flask应用是否主动添加Server头
排查你的Flask代码,确保没有自定义添加Server头的逻辑,比如:
# 这类代码需要删除 resp = make_response("Response content") resp.headers["Server"] = "Custom Server"
4. 验证配置
重启Gunicorn和Nginx后,用curl测试所有端点:
curl -I http://your-domain.com/ curl -I http://your-domain.com/any-other-endpoint
确认响应头中不再出现Server字段即可。
内容的提问来源于stack exchange,提问作者Juan C
相关产品推荐
相关产品推荐

