【问题标题】:nginx reverse proxy fails for post/get requestsnginx 反向代理对于 post/get 请求失败
【发布时间】:2017-02-27 03:43:33
【问题描述】:

我正在尝试使用 nginx 为 nodejs 应用程序设置反向代理。我的节点应用程序当前在 example.com 服务器的端口 8005 上运行。运行应用程序并访问 example.com:8005,应用程序运行良好。但是当我尝试设置 nginx 时,我的应用程序似乎首先通过访问 example.com/test/ 工作,但是当我尝试发布或获取请求时,请求想要使用 example.com:8005 url,我最终得到跨源错误,CORS。我想让请求 url 反映 nginx url,但我没有运气到达那里。下面是我的 nginx default.conf 文件。

server {
    listen       80;
    server_name  example;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

   location /test/ {
        proxy_pass http://localhost:8005/;
        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;
    }
}

【问题讨论】:

  • 您的 post/get 请求是否以 '/test/' 为前缀(它们是否属于 /test/ location 块)?
  • @roger no 我的帖子没有任何前缀
  • 如果是这样的话,我猜他们被“/”位置块(当前正在提供静态文件)捕获。如果您希望它们被您的节点进程拾取,您需要确保这些请求通过 proxy_pass localhost:8005 到达位置块
  • 此外,如果您希望您的请求达到此配置,它正在侦听端口 80(而不是 8005),因此在您的请求中不要在 url 末尾使用 :8005
  • 我正在从一个 html 页面提交一个简单的表单提交帖子,该页面由节点应用程序在端口 8005 上托管。我希望 nginx 能让我隐藏端口并最终让我托管多个应用程序在 example.com/test、example.com/test2 等下

标签: node.js express nginx reverse-proxy


【解决方案1】:

必须有某种方式告诉 nginx 你正在使用哪个应用程序。

因此,您可以使用 test(location /test/api_uri) 作为所有 api 的前缀,然后捕获所有带有前缀 /test 的 url 并将它们传递给节点,或者如果您的 urk 中有一些特定的模式,您可以使用正则表达式捕获该模式,例如假设所有 app1 api 都在其中某处包含 app1,然后使用 location ~ /.*app1.* {} location ~ /.*app2.* 捕获这些 url,确保您维护位置的 order

演示代码:

server {
   ...
   location /test {
      proxy_pass http://localhost:8005/; #app1
      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 /test2 {
      proxy_pass http://localhost:8006/; #app2
      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;
   }
   ...
}

正则表达式的其他演示,

server {
   ...
   location ~ /.*app1.* {
      proxy_pass http://localhost:8005/; #app1
      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 ~ /.*app2.* {
      proxy_pass http://localhost:8006/; #app2
      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;
   }
   ...
}

【讨论】:

    猜你喜欢
    • 2019-02-22
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2018-04-22
    • 1970-01-01
    • 2019-01-21
    相关资源
    最近更新 更多