Nginx反向代理到URI
问题描述:
我正在用nginx创建一个反向代理,用于在现有的遗留系统和基于Rails的新应用程序之间进行代理。我们默认将所有流量发送到Rails站点,除非它们匹配某些URL或者请求主体不包含某些参数。但是,有些情况下,网址与旧版条件匹配,但如果存在某些参数,我们需要重定向到新系统。因此,例如,我们有一个URL为/index.cfm?fuseaction=search
,通常会发送到旧系统,但由于它包含fuseaction=search
,我需要重定向到新系统/search/events
。我写了下面的配置。Nginx反向代理到URI
upstream legacy {
server 10.0.0.1:80;
}
upstream rails {
server 10.0.0.2:80;
}
server {
listen 0.0.0.0:80;
server_name mydomain.com
root /usr/share/nginx/html;
index index.html index.htm;
location/{
proxy_pass http://rails;
if ($request_body ~* fuseaction(?!=public\.search(_all(_by_type)?)?))
{
proxy_pass http://legacy;
}
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_redirect off;
proxy_buffering off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location ~* /(index.cfm|images|uploads|admin|htmlArea|innovastudio|js|scripts|w3c)*$ {
proxy_pass http://legacy;
if ($request_body ~* fuseaction=public\.search(_all(_by_type)?)?)
{
proxy_pass http://rails/search/events;
}
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_redirect off;
proxy_buffering off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
然而,当我尝试启动nginx的,我得到以下错误:
"proxy_pass" may not have URI part in location given by regular expression, or inside named location, or inside the "if" statement, or inside the "limit_except" block in /etc/nginx/sites-enabled/default:56
我明白什么是错误的说法,但我不知道如何解决它。也许proxy_pass
不是我所需要的?也许我需要使用proxy_redirect
?任何帮助我如何解决这个问题表示赞赏。
答
在试图理解这个问题的过程中,我意识到我真正需要的是一个重定向,而不是试图代理。除了我最终改变的许多事情外,我还检查了$args
变量而不是$request_body
。下面是重写块看时,我就完成
if ($args ~ fuseaction\=public\.race_search(_all(_by_type)?)?)
{
rewrite ^(.*)$ /search/events? permanent;
}
if ($args ~ fuseaction\=public\.tools)
{
rewrite ^(.*)$ /directors? permanent;
}
if ($args ~ fuseaction\=public\.contact)
{
rewrite ^(.*)$ /contact? permanent;
}
if ($args ~ fuseaction\=public\.spotlight)
{
rewrite ^(.*)$ /search/events? permanent;
}
if ($args ~ fuseaction\=public\.results)
{
rewrite ^(.*)$ /search/results? permanent;
}
的第一个参数的整个路径,第二告诉它如何重写匹配,与尾随?
从重写删除任何查询参数等,第三个做301(永久)重定向。
答
proxy_pass应该没问题,但我不知道为什么它在抱怨那条线,是“// rails”肯定是一个可访问的URI?
我会认为这个问题与使用$ request_body有关,如果您知道它们是您需要匹配的GET参数,那么我会切换到使用$ args。
喜欢的东西:
if ($args ~ "fuseaction(?!=public\.search(_all(_by_type)?)?)")
感谢您的回答。我已经知道了,但我忘了在这里回答我自己的问题。答案是使用重写进行重定向。 – 2013-06-30 21:10:18
哦,是的,你的答案的一部分是正确的。我也必须切换到'args'。从我所知道的request_body'总是空的或空的。 – 2013-06-30 21:15:42
我的荣幸,是重写,好点我错过了。 $ request_body可能不会包含太多,除非它是一个帖子。很高兴听到你解决它! RGDS .... Hoonto /马特 – hoonto 2013-06-30 21:27:42