2012-05-16 36 views
13

我是新來nginx的,從正在添加的Apache和我基本上要做到以下幾點:Nginx的代理或重寫取決於用戶代理

基於用戶代理: iPhone:重定向到iphone.mydomain.com

安卓重定向到android.mydomain.com

Facebook的:反向代理otherdomain.com

所有其他:重定向到...

,並嘗試了以下方式:

location /tvoice { 
    if ($http_user_agent ~ iPhone) { 
    rewrite  ^(.*) https://m.domain1.com$1 permanent; 
    } 
    ... 
    if ($http_user_agent ~ facebookexternalhit) { 
    proxy_pass   http://mydomain.com/api; 
    } 

    rewrite  /tvoice/(.*) http://mydomain.com/#!tvoice/$1 permanent; 
} 

但現在我開始nginx的時候得到一個錯誤:

nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" 

,我不知道要怎麼弄它還是什麼問題。

由於

回答

18

的proxy_pass靶的「/ API」部分是URI部分錯誤消息指的是。由於ifs是僞位置,並且具有uri部分的proxy_pass會用給定的uri替換匹配的位置,所以if不允許。如果你只是反轉,如果是邏輯,你可以得到這個工作:

location /tvoice { 
    if ($http_user_agent ~ iPhone) { 
    # return 301 is preferable to a rewrite when you're not actually rewriting anything 
    return 301 https://m.domain1.com$request_uri; 

    # if you're on an older version of nginx that doesn't support the above syntax, 
    # this rewrite is preferred over your original one: 
    # rewrite^https://m.domain.com$request_uri? permanent; 
    } 

    ... 

    if ($http_user_agent !~ facebookexternalhit) { 
    rewrite ^/tvoice/(.*) http://mydomain.com/#!tvoice/$1 permanent; 
    } 

    proxy_pass   http://mydomain.com/api; 
}