文章目录
- 前言
- 一、问题描述
- 二、问题原因
- 三、解决方案
- 3.1 启用 underscores_in_headers
- 3.2 重新加载 Nginx 配置
- 总结
前言
在日常开发和运维中,我们经常会使用 Nginx 作为反向代理服务器,将客户端的请求转发到后端服务。然而,在某些情况下,通过 Nginx 代理后,后端服务可能会丢失部分 HTTP 头部信息,尤其是包含下划线(_)的头部,例如 access_token。本文将详细介绍如何解决这一问题。
一、问题描述
今天遇到一个典型的问题:通过 Nginx 代理访问后端服务时,后端服务报错:
该接口的认证类型为授权码认证类型,请在请求头中添加 access_token 参数
直接访问后端服务的地址可以正常返回数据,但通过 Nginx 代理后却报错。经过排查,发现是 access_token 头部在代理过程中丢失了。
二、问题原因
Nginx 默认会忽略包含下划线(_)的 HTTP 头部。这是因为下划线在 HTTP 头部中是非标准的字符,可能会导致某些服务器或客户端无法正确处理。因此,Nginx 默认会丢弃这些头部。
三、解决方案
3.1 启用 underscores_in_headers
为了让 Nginx 能够传递包含下划线的头部,需要在 Nginx 配置中启用 underscores_in_headers 指令。需要注意的是,这个指令必须放在 http 块或 server 块中,而不能放在 location 块中。
修改 Nginx 配置文件(通常是 /etc/nginx/nginx.conf 或 /etc/nginx/conf.d/default.conf):
http {# 允许传递包含下划线的头部underscores_in_headers on;server {listen 80;server_name your_domain.com;location /proxy-data/ {proxy_pass http://172.17.17.17:18081;proxy_pass_request_headers on;# 可选:转发特定的 headerproxy_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;}}
}
3.2 重新加载 Nginx 配置
修改配置文件后,测试配置文件是否正确,并重新加载 Nginx:
./nginx -t # 测试配置文件是否正确
./nginx -s reload # 重新加载 Nginx
总结
通过启用 underscores_in_headers 指令,可以解决 Nginx 代理后 HTTP 头部丢失的问题。
具体步骤如下:
- 在 http 块或 server 块中添加 underscores_in_headers on
- 重新加载 Nginx 配置
- 验证配置是否生效
https://i-blog.csdnimg.cn/direct/f12e9ac6d5ab416cb8d5e2c1f5174ccd.jpeg#pic_center" alt="在这里插入图片描述" />