nginx 配置下“IF”块中“sub_filter”的使用

nginx 配置下“IF”块中“sub_filter”的使用

我将 nginx 作为多个应用程序的反向代理服务器,这些应用程序运行在不同的程序服务器上。我想将特定的 html/script 引入到设置预注册 URL 的响应内容中。这些 URL 可能属于 nginx 后面的任何应用程序。为此,我为所有 URL 使用 sub_filter,它运行良好。但是当我尝试将“sub_filter”放入“IF”块中时,它现在允许了。

我需要像下面这样的东西。

 resolver 8.8.8.8;
 proxy_pass http://www.example.com;
 proxy_set_header Accept-Encoding *;
 gunzip on;
if ( $induceScript = 1) {

                       sub_filter "</body>" "<div class='induced' <font color=red size=8>Induced Text </font></div></body>";
                       sub_filter_types *;
                       sub_filter_once off;

                    }

当我尝试重新启动 nginx 时显示以下错误消息。

nginx: [emerg] "sub_filter" directive is not allowed here in /etc/openresty/openresty.conf

从这里,如果我理解正确,“IF”指令不允许“sub_fiter”在其中。有什么具体原因吗?也提供正确的方法/替代方法来解决这个问题。

答案1

出现此错误的原因是,sub_filter除了以下内容之外,任何其他指令都不允许使用该指令:http, server, location
摘自http://nginx.org/en/docs/http/ngx_http_sub_module.html#sub_filter

server {
        listen 82;
        listen 83;
        server_name example.com;
        root /var/www/9000;
        try_files $uri $uri/index.html;
        sub_filter "</body>" $conditional_filter;
        sub_filter_types *;
        sub_filter_once off;
}
map $server_port $conditional_filter {
        82      "<br>Added content</body>";
        default "</body>";
}

您需要用指令替换ifmap
此示例中,我根据服务器/网站的端口添加了其他内容。
http://example.com:82结果内容类似于<body>abc</body>
where http://example.com:83results in following content <body>abc<br>Added content</body>。您可以使用自己的变量或其他条件
来代替。$server_port$induceScript

相关内容