0
server {
    listen 80;
    server_name ~^(?<custom>.+)\.(test)?website\.com$;

    location ~ ^/event/(\d+)$ {
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_intercept_errors on;

        # This is the problematic block
        # This conditional breaks the whole location block.
        # If I commented the if statement, the default proxy_pass works.
        if ($http_user_agent ~* iphone|android) {
            # the proxy_pass indeed works, tested on development machine
            proxy_pass http://frontends/userland/mobile/event/$1;
            break;
        }

        # When above if conditional is enabled, this fails.
        proxy_pass http://frontends/userland/event/$1;
    }
}

server_name 内のサブドメイン マッチャーはほとんどワイルドカードであることに気付きました。

if 条件が機能しないのはなぜですか? 私がやっていることが間違っている場合、それを書き直す最良の方法は何ですか?

Nginx バージョン: 1.2.0

4

2 に答える 2

2

^/event/(\d+)$条件で評価することによりiphone|android、PCRE キャプチャを上書きしますif。そのため、書き換えルールが実行された後、$1変数は空になります。

次のようなことを試してください:

    set $num $1;
    if ($http_user_agent ~* iphone|android) {
        proxy_pass http://frontends/userland/mobile/event/$num;
    }

    proxy_pass http://frontends/userland/event/$num;
于 2012-06-05T12:10:05.647 に答える
0

thisとthisを参照してください。特に、 Nginx で "if" がなぜ悪になり得るのかについては、こちらを参照してください。

物事が継承される方法は、期待される形式に従わないことが多く、「return」や「rewrite」(「last」を使用) などのディレクティブは、Nginx の「if」ブロック内で使用する唯一の本当に信頼できるものです。

代わりに次のようなことを試します。

server {
    listen 80;
    server_name ~^(?<custom>.+)\.(test)?website\.com$;

    location ~ ^/event/(\d+)$ {
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_intercept_errors on;

        if ($http_user_agent ~* iphone|android) {
            return 302 http://frontends/userland/mobile/event/$1;
            # Alternative syntax which should keep original url in browser
            #rewrite ^ http://frontends/userland/mobile/event/$1 last;
        }

        proxy_pass http://frontends/userland/event/$1;
    }
}
于 2012-06-04T16:39:34.547 に答える