有时候, 我们可能有修改 Nginx 默认 Header 的需求. 本文就将常见的方法列出来供大家参考.
修改普通请求的 Header
Nginx 内置的模块暂时仅支持修改响应头, 使用 add_header. 其中:
add_header 来自内置模块 ngx_http_headers_module, 用于设置 response header. 参考: http://www.cnblogs.com/linxiong945/p/4174262.html
如果需要设置普通请求的 request header, 则需要单独安装 headers-more-nginx-module 模块. 该模块提供了 more_set_headers,more_set_input_headers 分别用于设置请求, 响应头.
示例:
- location ~ .*\.(PHP|php5)?$ {
- fastcgi_pass 127.0.0.1:9000;
- fastcgi_index index.PHP;
- fastcgi_param LOG_ID $request_id;
- more_set_input_headers "Cookie: name=hello";
- more_set_headers "X-Powered-By:PHP";
- add_header X-Powered-By2 'PHP';
- include fastcgi.conf;
- }
修改反向代理请求的 Header
需要使用到 proxy_set_header 和 add_header 指令. 其中:
proxy_set_header 来自内置模块 ngx_http_proxy_module,
用来重定义发往代理服务器服务器的请求头. 参考:
示例:
- location ^~/test/ {
- proxy_pass http://127.0.0.1:8001$request_uri;
- proxy_set_header host $http_host;
- proxy_set_header x-real-ip $remote_addr;
- proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
- }
headers-more-nginx-module 模块
headers-more-nginx-module 模块用于添加, 修改或清除 请求 / 响应头, 该模块不是 nginx 自带的, 默认不包含该模块, 需要另外安装.
GitHub 地址:
安装:
- $ wget 'http://nginx.org/download/nginx-1.13.6.tar.gz'
- $ tar -xzvf nginx-1.13.6.tar.gz
- $ cd nginx-1.13.6/
- # 假设 Nginx 安装在 /opt/nginx/ 目录
- $ ./configure --prefix=/opt/nginx \
- --add-module=/path/to/headers-more-nginx-module
- $ make -j2
- $ make install
从 NGINX 1.9.11 开始, 可以使用动态模块加载 (生成. so 文件, 无需重启 Nginx 整个服务):
- $ ./configure --prefix=/opt/nginx \
- --add-dynamic-module=/path/to/headers-more-nginx-module
在 Nginx 配置文件里加上:
load_module /path/to/modules/ngx_http_headers_more_filter_module.so;
具体安装流程及细节步骤参考: Nginx 安装 echo 模块 https://www.cnblogs.com/52fhy/p/10166333.html . 因为是类似的.
该模块主要有 4 个指令:
more_set_headers 用于添加, 修改, 清除响应头
more_clear_headers 用于清除响应头
more_set_input_headers 用于添加, 修改, 清除请求头
more_clear_input_headers 用于清除请求头
示例:
- # set the Server output header
- more_set_headers 'Server: my-server';
- # set and clear output headers
- location /bar {
- more_set_headers 'X-MyHeader: blah' 'X-MyHeader2: foo';
- more_set_headers -t 'text/plain text/CSS' 'Content-Type: text/foo';
- more_set_headers -s '400 404 500 503' -s 413 'Foo: Bar';
- more_clear_headers 'Content-Type';
- # your proxy_pass/memcached_pass/or any other config goes here...
- }
- # set output headers
- location /type {
- more_set_headers 'Content-Type: text/plain';
- # ...
- }
- # set input headers
- location /foo {
- set $my_host 'my dog';
- more_set_input_headers 'Host: $my_host';
- more_set_input_headers -t 'text/plain' 'X-Foo: bah';
- # now $host and $http_host have their new values...
- # ...
- }
- # replace input header X-Foo *only* if it already exists
- more_set_input_headers -r 'X-Foo: howdy';
参考
1,[随笔] nginx add_header 指令的使用 - linxiong - 博客园
http://www.cnblogs.com/linxiong945/p/4174262.html
2,nginx 的 headers_more 模块的使用 - chunyuan314 的博客 - CSDN 博客
3, 关于 nginx 中 proxy_set_header 的设置 - 七号空间 - CSDN 博客
来源: https://www.cnblogs.com/52fhy/p/10166352.html