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

时间:2018-11-14 09:10:10

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

我有一个Laravel应用程序,其中一个路由/ onlineAds会将我带到以Vue.Js为前端,Node.js为Back生成的另一应用程序(SPA)。因此,我试图将Nginx用作反向代理,以便为SpaApp的静态文件提供服务,但没有成功。

我的conf如下:

/                   =>      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;
  }
}

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

正则表达式中的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一起使用。关于if的使用,请参见this caution


假设URI /js/foo.js可以位于C:/laragon/www/laravel_App/public/js/foo.jsC:/laragon/www/craiglist/dist/js/foo.js中,则可以要求Nginx使用try_files和公共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;
}