2

几个月来我一直在寻找这个答案,但一直无法解决这个问题。我使用 nginx 作为我的 web 服务器,使用 node.js 作为我的后端 apis 和 vue 作为我使用 webpack 的主要前端网页。我希望能够通过访问 http://ip 访问我的 Vue 页面,然后通过访问http://ip/api访问 api 服务。我没有设置域名,所以我使用 IP 地址作为 url。

到目前为止,我构建了我的 Vue 应用程序并位于 /var/www/html/Web/dist 文件夹中,如果您转到http://ip url,它可以工作,但我无法访问我的 node.js API。我的 node.js 服务器在 localhost 端口 3000 上运行。我的 nginx 配置如下所示:

server {
        listen 80;

        root /var/www/html/Web/dist;
}

server {

listen 80;

  location /api/ {

        proxy_pass http://localhost:3000;
        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;

  }

}
4

1 回答 1

2

您正在复制服务器配置。只需保留一个服务器属性集:

server {
  listen 80;    
  root /var/www/html/Web/dist;
  location /api/ {    
        proxy_pass http://localhost:3000;
        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;

  }
}

这意味着:

  • 监听端口 80 上所有 ip 的所有请求
  • 从根评估相对路径/var/www/html/Web/dist;
  • 如果 url 中有匹配的 '/api/' 将其传递给 localhost:3000

它现在应该可以按预期工作

于 2018-12-10T00:22:54.180 回答