问题描述
我是新的到nginx,从apache和我基本上想做以下:
基于用户代理:
iPhone:redirect到iphone.mydomain.com
android:重定向到android.mydomain.com
facebook:reverse proxy otherdomain.com
所有其他:重定向到...
并尝试使用以下方式: p>
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:[proxy]proxy_pass不能在由正则表达式或命名位置或if语句内部给定的位置中具有URI部分,里面limit_except
我不知道该怎么做或问题是什么。
感谢
proxy_pass目标的'/ api'引用错误消息的URI部分。由于ifs是伪位置,而proxy_pass和uri部分用给定的uri替换匹配的位置,因此不允许在if中。如果你只是反转if的逻辑,你可以让这个工作:
location / tvoice {
if http_user_agent〜iPhone){
#return 301比没有重写的时候更好的重写
return 301 https://m.domain1.com$request_uri;
#如果你使用的是不支持上述语法的旧版本的nginx,
#这种重写优于原来的:
#rewrite ^ https ://m.domain.com$request_uri?常驻;
}
...
if($ http_user_agent!〜facebookexternalhit){
rewrite ^ / tvoice /(.*)http:// mydomain.com/#!tvoice/$1 permanent;
}
proxy_pass http://mydomain.com/api;
}
i'm new to nginx, comming from apache and i basically want to do the following:
Based on user-agent:iPhone: redirect to iphone.mydomain.com
android: redirect to android.mydomain.com
facebook: reverse proxy to otherdomain.com
all other: redirect to ...
and tried it the following way:
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;
}
But now i get an error when starting 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"
And i dont get how to do it or what the problem is.
Thanks
The '/api' part of the proxy_pass target is the URI part the error message is referring to. Since ifs are pseudo-locations, and proxy_pass with a uri part replaces the matched location with the given uri, it's not allowed in an if. If you just invert that if's logic, you can get this to work:
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;
}
这篇关于Nginx代理或重写取决于用户代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!