如何在gunicorn搭配uvicorn worker类时修改/隐藏Server HTTP头?
解决Gunicorn搭配Uvicorn Worker时隐藏/修改Server HTTP头的问题
当用Gunicorn运行Uvicorn Worker时,--no-server-header参数失效是因为两个层面的问题:Uvicorn Worker的参数需要通过Gunicorn配置传递,同时Gunicorn自身也会添加Server头。以下是具体解决步骤:
1. 禁用Uvicorn的Server头
在你的gunicorn_conf.py配置文件中,通过worker_kwargs给Uvicorn Worker传递禁用Server头的参数:
worker_class = "uvicorn.workers.UvicornWorker" worker_kwargs = { "server_header": False }
这样Uvicorn就不会再添加Server: uvicorn/x.x.x这类响应头。
2. 处理Gunicorn自带的Server头
Gunicorn默认会添加Server: gunicorn/x.x.x的响应头,你可以通过以下两种方式处理:
方式一:ASGI中间件(推荐用于FastAPI/Starlette应用)
在你的ASGI应用入口文件(比如my.asgi)中添加全局中间件,直接修改或移除响应头:
# 以FastAPI为例,其他ASGI框架逻辑类似 from fastapi import FastAPI from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request from starlette.responses import Response app = FastAPI() class ModifyServerHeaderMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): response = await call_next(request) # 移除Server头 response.headers.pop("Server", None) # 若要自定义头内容,替换为下面一行 # response.headers["Server"] = "YourCustomServer/1.0" return response app.add_middleware(ModifyServerHeaderMiddleware)
方式二:Gunicorn配置函数
在gunicorn_conf.py中定义自定义响应头处理函数,移除Gunicorn添加的Server头:
def customize_response_headers(response): del response.headers["Server"] return response header_func = customize_response_headers
3. 验证结果
重启Gunicorn服务后,用curl命令检查响应头:
curl -I http://your-app-domain:port
此时应该看不到Server响应头,或者看到你自定义的内容。
内容的提问来源于stack exchange,提问作者sgargel
相关产品推荐
相关产品推荐

