在nginx中配置重写规则

时间:2015-07-03 09:35:26

标签: nginx url-rewriting url-redirection

我在端口80上运行了ngnix webserver。我有一个在9000端口上运行的Nodejs。我需要将来自我的nginx的请求重写为在端口3000上运行的应用服务器。

我尝试使用以下选项进行配置,但它会重定向到浏览器而不转发到应用服务器。当有对/hosts.json的请求时,需要将其重定向到http://appserver.corp.cn.com:3000/hosts/hosts.json。请让我知道我哪里出错了。

server {
listen       80;
server_name  localhost;
access_log  /var/log/nginx/localhost.access.log;
location / {
             rewrite ^/hosts.json http://appserver.corp.cn.com:3000/hosts.json permanent;
             rewrite ^/hosts/bu.json http://appserver.corp.cn.com:3000/hosts/bu.json permanent;
             proxy_pass http://localhost:9000;
             proxy_http_version 1.1;
             proxy_set_header Upgrade $http_upgrade;
             proxy_set_header Connection 'upgrade';
             proxy_set_header Host $host;
             proxy_cache_bypass $http_upgrade;
    }
}

我需要为以下网址格式设置proxy_pass

location  ~ ^/hosts/bu/(.*)/app/(.*)$ {
  proxy_pass   http://appserver.cnma.com:3000/hosts/bu/$1/app/$2;
}

1 个答案:

答案 0 :(得分:2)

您希望基于URI代理到不同的服务器。有一种自然的方法,只需在适当的proxy_pass s中输出不同的location指令:

server {
  ...

  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection 'upgrade';
  proxy_set_header Host $host;
  proxy_cache_bypass $http_upgrade;

  location / {
    proxy_pass http://localhost:9000;
  }

  location /hosts.json {
    proxy_pass http://appserver.corp.cn.com:3000;
  }

  location /hosts/bu.json {
    proxy_pass http://appserver.corp.cn.com:3000;
  }

  location /hosts/bu/ {
    proxy_pass http://appserver.corp.cn.com:3000;
  }
}