有时候,咱们可能有修改Nginx默认Header的需求。本文就将常见的方法列出来供你们参考。php
Nginx内置的模块暂时仅支持修改响应头,使用add_header
。其中:css
add_header
来自内置模块ngx_http_headers_module
,用于设置response header。参考:http://www.cnblogs.com/linxiong945/p/4174262.htmlhtml
若是须要设置普通请求的request header,则须要单独安装headers-more-nginx-module
模块。该模块提供了more_set_headers
,more_set_input_headers
分别用于设置请求、响应头。nginx
示例:git
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; }
须要使用到proxy_set_header
和add_header
指令。其中:github
proxy_set_header
来自内置模块ngx_http_proxy_module
,
用来重定义发往代理服务器服务器的请求头。参考:https://blog.csdn.net/weixin_41585557/article/details/82426784bash
示例:服务器
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 模块用于添加、修改或清除 请求/响应头,该模块不是nginx自带的,默认不包含该模块,须要另外安装。memcached
Github地址:https://github.com/openresty/headers-more-nginx-module.net
安装:
$ 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模块 http://www.javashuo.com/article/p-geevpvfz-gr.html 。由于是相似的。
该模块主要有4个指令:
示例:
# 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';
一、【随笔】nginx add_header指令的使用 - linxiong - 博客园
http://www.cnblogs.com/linxiong945/p/4174262.html
二、nginx的headers_more模块的使用 - chunyuan314的博客 - CSDN博客
https://blog.csdn.net/chunyuan314/article/details/81737303
三、关于nginx中proxy_set_header的设置 - 七号空间 - CSDN博客
https://blog.csdn.net/weixin_41585557/article/details/82426784