node.js - Nginx 反向代理 服务 Node.js 应用程序静态文件

标签 node.js nginx vue.js single-page-application nginx-reverse-proxy

我有一个 Laravel 应用程序,其中一条路线/onlineAds 将带我到另一个使用 Vue.Js 作为前端、Node.js 作为后端构建的应用程序(一个 SPA)。因此,我尝试使用 Nginx 作为反向代理来服务我的 SpaApp 的静态文件,但没有成功。

我的配置如下:

/                   =>      will be serverd from "C:/laragon/www/laravel_App/public/"
/onlineAds/(*)      =>      will be serverd from "C:/laragon/www/VueNodeApp/dist/"
/api/(*)            =>      will be proxied to nodeJs server

这是我尝试使用 Nginx 做的事情:

server {
  listen 8080;
  server_name domain.test *.domain.test;
  root "C:/laragon/www/laravel_App/public/";

  index index.html index.htm index.php;

  location / {
      try_files $uri $uri/ /index.php$is_args$args;
      autoindex on;
  }

  location ~* ^\/onlineAds(.*)$ {
      alias "C:/laragon/www/craiglist/dist/";
      #try_files $uri $uri/ /index.html;
  }

  location ~* ^\/api(.*)$ {
      proxy_set_header        Host $host;
      proxy_set_header        Upgrade $http_upgrade;
      proxy_set_header        Connection 'upgrade';
      proxy_set_header        X-Real-IP $remote_addr;
      proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header        X-Forwarded-Proto $scheme;

      proxy_read_timeout      300;
      proxy_pass              http://localhost:8081;
  }

  location ~ \.php$ {
      include snippets/fastcgi-php.conf;
      fastcgi_pass php_upstream;        
      #fastcgi_pass unix:/run/php/php7.0-fpm.sock;
  }


  charset utf-8;

  location = /favicon.ico { access_log off; log_not_found off; }
  location = /robots.txt  { access_log off; log_not_found off; }
  location ~ /\.ht {
      deny all;
  }
}

我做错了什么?

最佳答案

正则表达式中的alias语句location需要文件的完整路径。请参阅this document了解详情。

例如:

location ~* ^\/onlineAds(.*)$ {
    alias "C:/laragon/www/craiglist/dist$1";
    if (!-e $request_filename) { rewrite ^ /onlineAds/index.html last; }
}

由于this issue,避免将try_filesalias一起使用。请参阅this caution关于 if 的使用。

<小时/>

假设 URI /js/foo.js 可能位于 C:/larragon/www/laravel_App/public/js/foo.jsC:/larragon/www/craiglist/dist/js/foo.js,您可以要求 Nginx 使用 try_files 和公共(public) root 目录尝试这两个位置。

例如:

location /js/ {
    root "C:/laragon/www";
    try_files /laravel_App/public$uri /craiglist/dist$uri =404;
}
location /css/ {
    root "C:/laragon/www";
    try_files /laravel_App/public$uri /craiglist/dist$uri =404;
}

关于node.js - Nginx 反向代理 服务 Node.js 应用程序静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53296509/

相关文章:

node.js - Node.js 的跨浏览器 COMET 实现

ruby-on-rails - 调试 502 Bad Gateway 错误 - Ubuntu、Nginx、Unicorn

php - 将所有内容传递到一个位置 nginx

ruby-on-rails-4 - 带有运行 Puma 和 Nginx 的 AWS Elastic Beanstalk 的 Rails 应用程序 502

vue.js - 如何使用提供/注入(inject) TypeScript 但没有 vue-class-component

javascript - 替换嵌套数组中的对象

node.js - Mongoose 嵌套架构 CastError

node.js - 在发布请求传输 Node/express js期间保护客户端/服务器之间的请求有效负载的最佳实践

javascript - 在 Firebase 中创建用户给我一个错误

Node.js - 使用 Multer 如何获取上传文件(源文件)的完整路径?