Configuration Nginx代理或重写,具体取决于用户代理

Configuration Nginx代理或重写,具体取决于用户代理,configuration,nginx,user-agent,Configuration,Nginx,User Agent,我是nginx新手,来自apache,我主要想做以下工作: 基于用户代理: iPhone:重定向到iPhone.mydomain.com android:重定向到android.mydomain.com facebook:反向代理到otherdomain.com 所有其他:重定向到 并尝试了以下方法: location /tvoice { if ($http_user_agent ~ iPhone ) { rewrite ^(.*) https://m.domain1.

我是nginx新手,来自apache,我主要想做以下工作:

基于用户代理: iPhone:重定向到iPhone.mydomain.com

android:重定向到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"
我不知道该怎么做,也不知道问题出在哪里


谢谢

代理传递目标的'/api'部分是错误消息所指的URI部分。由于ifs是伪位置,并且带有uri部分的proxy_pass用给定的uri替换匹配的位置,因此在if中不允许这样做。如果你只是颠倒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;
}