NGINX 反向代理用于替换响应正文中的特定关键字

问题描述 投票:0回答:1

我想替换text/html内容类型页面的响应正文中的特定文本。

我为此使用 NGINX 反向代理设置。当我点击 NGINX 基本 URL 时,它会重定向到 https://www.google.com 但未通过 NGINX 接收响应。所以我无法替换回复中的文本。

对于重定向,我使用了 Proxy_Pass,rewrite 指令。 对于文本替换,我使用了 sub_filter 指令

当我在 Tomcat 服务器中运行的本地计算机上尝试这种方法时,它起作用了。但是当我在 https://www.google.com 上尝试这个时,它不起作用。

我需要有关如何使用我的 NGINX 服务器重定向 https://www.google.com 并将响应返回到 NGINX 服务器的帮助。

这是我的 NGINX 反向代理配置。在所有配置中,重定向都有效,但未通过 NGINX 服务器收到响应。

配置1:

server {
    listen       85;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        root   html;
        index  index.html index.htm;
        rewrite ^/(.*)$ https://www.google.com/$1 permanent;
        sub_filter '</body>' '</body><div><p>Replace success</p></div>';
        sub_filter_once off;
    }

配置2:

server {
    listen       85;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        root   html;
        index  index.html index.htm;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass https://www.google.com;
    sub_filter '</body>' '</body><div><p>test</p></div>';
        sub_filter_once off;
    }

配置3:

server {
    listen       85;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        root   html;
        index  index.html index.htm;
    add_header Access-Control-Allow-Origin $http_origin;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-NginX-Proxy true;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass https://www.google.com;
    sub_filter '</body>' '</body><div><p>test</p></div>';
        sub_filter_once off;
    }

配置4:

    upstream test {
    ip_hash;
    server google.com:443;
}

server {
    listen       85;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        root   html;
        index  index.html index.htm;
    proxy_pass https:test;
    add_header Access-Control-Allow-Origin $http_origin;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-NginX-Proxy true;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;    
    sub_filter '</body>' '</body><div><p>test</p></div>';
        sub_filter_once off;
    }
nginx redirect url-rewriting reverse-proxy proxypass
1个回答
0
投票

原因可能是因为 proxy_pass 目的地,例如。谷歌已启用 gzip。您可以通过各种网站(https://www.giftofspeed.com/gzip-test/)进行检查,或者查看响应的标头。启用 gzip 后,sub_filter 无法找到搜索和替换字符串,这就是为什么什么也没有发生。

© www.soinside.com 2019 - 2024. All rights reserved.