重写 HTTP 响应

基本配置

location / {
    proxy_pass http://127.0.0.1:8080;

    sub_filter_once on;
    sub_filter_types text/html text/css;
    sub_filter 'text/html; charset=iso-8859-1' 'text/html; charset=utf-8';
    sub_filter '<a href="http://127.0.0.1:8080/'  '<a href="https://$host/';
}

基本配置说明

  • sub_filter_once on:只替换第一次匹配
  • sub_filter_types text/html text/css:指定替换的内容类型
  • sub_filter 'text/html; charset=iso-8859-1' 'text/html; charset=utf-8':替换字符集
  • sub_filter '<a href="http://127.0.0.1:8080/' '<a href="https://$host/':替换链接

基本配置原理sub_filter 指令用于替换响应体中的内容,可以用于修改响应体中的链接、字符集等。

修改响应头

location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

修改响应头说明

  • proxy_set_header Host $host:修改 Host 响应头
  • proxy_set_header X-Real-IP $remote_addr:添加 X-Real-IP 响应头

修改响应头原理proxy_set_header 指令用于修改请求头,可以用于修改 Host、添加自定义响应头等。

修改响应体

location / {
    proxy_pass http://127.0.0.1:8080;
    sub_filter 'server: http://127.0.0.1:8080' 'server: https://$host';
}

修改响应体说明

  • sub_filter 'server: http://127.0.0.1:8080' 'server: https://$host':替换响应体中的内容

修改响应体原理sub_filter 指令用于替换响应体中的内容,可以用于修改响应体中的链接、字符集等。

修改状态码

error_page 404 =301 /index.php;

修改状态码说明

  • error_page 404 =301 /index.php:将 404 错误码修改为 301

修改状态码原理error_page 指令用于定义错误页面,可以用于修改错误码。

添加响应头

location / {
    proxy_pass http://127.0.0.1:8080;
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
    add_header X-XSS-Protection "1; mode=block";
}

添加响应头说明

  • add_header X-Frame-Options "SAMEORIGIN":添加 X-Frame-Options 响应头
  • add_header X-Content-Type-Options "nosniff":添加 X-Content-Type-Options 响应头
  • add_header X-XSS-Protection "1; mode=block":添加 X-XSS-Protection 响应头

添加响应头原理add_header 指令用于添加响应头,可以用于添加安全响应头、自定义响应头等。

删除响应头

location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_hide_header X-Powered-By;
}

删除响应头说明

  • proxy_hide_header X-Powered-By:删除 X-Powered-By 响应头

删除响应头原理proxy_hide_header 指令用于删除响应头,可以用于删除敏感信息、不必要的响应头等。