Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Nginx 文本替換模塊 Substitution:響應體內容搜索替換實戰

編輯:Linux 教學

ngx_http_sub_module 允許在 Nginx 響應體中搜索並替換文本。編譯需加 --with-http_sub_module。

配置示例

location / {
    sub_filter '' '';
    sub_filter_once on;   # on 只替換第一次匹配,off 替換所有匹配
}

指令詳解

指令語法默認值作用域說明
sub_filtersub_filter 原文本 新文本nonehttp, server, location匹配不區分大小寫,新文本可包含變量,每個 location 僅能指定一條規則
sub_filter_onceon | offonhttp, server, locationoff 替換所有出現處
sub_filter_typesmime-type ...text/htmlhttp, server, location指定檢查的 MIME 類型

應用場景

  • 注入統計代碼、廣告腳本到 HTML 頁面。
  • 修正後端返回的錯誤鏈接/路徑(如 CDN 域名替換)。
  • 移除/替換敏感信息(如內部 IP、調試標記)。

注意:若響應體被壓縮(gzip),需先關閉壓縮或在解壓後處理,否則無法匹配文本。

Copyright © Windows教程網 All Rights Reserved