configuration - Nginx 代理或重写取决于用户代理

标签 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.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"

我不知道该怎么做或问题是什么。

谢谢

最佳答案

proxy_pass 目标的“/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;
}

关于configuration - Nginx 代理或重写取决于用户代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10627596/

相关文章:

c# - 使用 C# 的 CSharpScript 从另一个程序集中的字符串设置局部变量

nginx - 你如何配置nginx(dev分支)拒绝使用低于TLS1.1的?

javascript - Javascript `userAgent` 与浏览器的 header 请求不同吗

webserver - 为什么有些服务器会响应 503 错误,除非我的用户代理以 "Mozilla"开头?

java - PropertyPlaceholderConfigurer 与 Hibernate.cfg.xml

file - sails 记录到文件

docker - 通过域自动访问 Docker 容器并在 Windows 上支持 SSL/HTTPS

ubuntu - 卸载nginx?

android - 将 user-agent 中的 appname 替换为 volley

java - 如何从jboss数据库配置中获取密码