nginx 条件代理通行证 [英] nginx conditional proxy pass

查看:31
本文介绍了nginx 条件代理通行证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试配置 nginx 以代理将请求传递到另一台服务器,仅当 $request_body 变量匹配特定的正则表达式时.

i am trying to configure nginx to proxy pass the request to another server, only if the $request_body variable matches on a specific regular expression.

我现在的问题是,我不知道如何准确配置此行为.

My problem now is, that I don't how to configure this behaviour exactly.

我目前正在做这个:

server {
    listen 80 default;
    server_name test.local;

    location / {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $http_host;

            if ($request_body ~* ^(.*).test) {
                    proxy_pass http://www.google.de;
            }

            root /srv/http;
    }

}

但这里的问题是,root 总是占上风.代理不会通过任何一种方式.

but the problem here is, that root has always the upperhand. the proxy won't be passed either way.

对我如何做到这一点有任何想法吗?

any idea on how I could accomplish this?

提前致谢

推荐答案

Nginx 路由基于与请求 URI 匹配的位置指令.解决方案是临时修改这个,以便将请求转发到不同的端点.

Nginx routing is based on the location directive which matches on the Request URI. The solution is to temporarily modify this in order to forward the request to different endpoints.

server {
    listen 80 default;
    server_name test.local;

     if ($request_body ~* ^(.*).test) {
         rewrite ^(.*)$ /istest/$1;
     }

     location / {
         root /srv/http;
     }

     location /istest/ {
        rewrite ^/istest/(.*)$  $1 break;

        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $http_host;
        proxy_pass http://www.google.de;

    }
}

if 条件只能安全地在 Nginx 中使用 重写模块,它是它的一部分.在这个例子中.rewrite 在请求 URI 前面加上 istest 前缀.

The if condition can only safely be used in Nginx with the rewrite module which it is part of. In this example. The rewrite prefixes the Request URI with istest.

location 块优先考虑最接近的匹配.任何匹配 /istest/ 的都将转到第二个块,该块使用另一个 rewrite 从请求 URI 中删除 /istest/,然后再转发到上游代理.

The location blocks give precedence to the closest match. Anything matching /istest/ will go to the second block which uses another rewrite to remove /istest/ from the Request URI before forwarding to the upstream proxy.

这篇关于nginx 条件代理通行证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆