nginx 還能修改 http 響應體內容
-
ngx_http_sub_module模塊可以通過字符串替換的方式修改響應體內容。默認未安裝,需要在 configure 階段指定--with-http_sub_module參數。 -
sub_filter指令用於替換響應內容,語法格式爲sub_filter string replacement,string 表示被替換內容,replacement 爲替換後的內容。可配置在http, server, location塊中。 -
sub_filter_once指令用於設置查找到的字符串僅替換一次還是全部替換。語法爲sub_filter_once on | off, 默認值 on 表示僅替換一次,off 表示全部替換。 -
sub_filter_last_modified指令用於控制在使用 sub_filter 修改響應體內容後原始響應頭中 Last-Modified 字段是否保留。默認值 off 表示不保留,on 表示保留。語法爲sub_filter_last_modified on | off。 -
測試
-
將
Thank you改爲Thanksserver { listen 80; server_name localhost; location / { root html; sub_filter 'Thank you' 'Thanks'; } } -
將 nginx 全部替換爲 NGINX
server { listen 80; server_name localhost; location / { root html; sub_filter 'nginx' 'NGINX'; sub_filter_once off; } } -
同時修改多項內容
server { listen 80; server_name localhost; location / { root html; sub_filter 'nginx''NGINX'; sub_filter '<head>''<head><meta charset="UTF-8">'; sub_filter 'server''服務器'; sub_filter 'Welcome to''歡迎來到'; sub_filter_once off; } } -
修改代理返回的內容
server { listen 80; server_name localhost; location / { root html; sub_filter 'nginx''NGINX'; sub_filter '<head>''<head><meta charset="UTF-8">'; sub_filter 'server''服務器'; sub_filter 'Welcome to''歡迎來到'; sub_filter_once off; } location /api/ { proxy_pass http://192.168.1.16:8086/; sub_filter '-''/'; sub_filter_once off; } }
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/F5mETByCuuzHUgJcYKn7nQ