nginx修改響應頭(可屏蔽后端服務器的信息:IIS,PHP等)


修改nginx反向代理請求的Header

需要使用到proxy_set_headeradd_header指令。其中:

proxy_set_header 來自內置模塊ngx_http_proxy_module
用來重定義發往代理服務器服務器的請求頭。參考:https://blog.csdn.net/weixin_41585557/article/details/82426784

示例:

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地址:https://github.com/openresty/headers-more-nginx-module

安裝:

$  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
$  make install

在Nginx配置文件里加上:

load_module /path/to/modules/ngx_http_headers_more_filter_module.so;
該模塊主要有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';

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM