使用 Nginx 加载 CSS 和 Js 文件

Load CSS and Js files with Nginx

我正在尝试在 Nginx 中为 Angular 部署的站点提供服务(我有一个带有 index.html 文件的 dist 目录)。在那个目录中我有:

我没有使用 Nginx 的经验,所以我正在努力正确地为这个网站提供服务。我对该站点的配置是:

server {
    listen  80;
    server_name sibdomain.domain.com;

    location ~* \.(?:css|js|map|jpe?g|gif|png)$ { }

    location / {
        root  /var/www/multiapp/dist;
        index  index.html index.htm;
        try_files $uri $uri/ =404;
         if (!-e $request_filename){
             rewrite ^(.*)$ /index.html?path= break;
         }
    }

    error_page  500 502 503 504  /50x.html;
    location = /50x.html {
        root  /var/www/multiapp/dist;
    }
}

现在索引中加载的唯一文件,但是 css 和 js 文件 return 404。在 apache 中这个站点工作正常,我有这个规则:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# not rewrite css, js and images
RewriteCond %{REQUEST_URI} !\.(?:css|js|map|jpe?g|gif|png)$ [NC]
RewriteRule ^(.*)$ index.html?path= [NC,L,QSA]

我使用了 this site,他们为我提供了这个翻译:

# nginx configuration 
  location ~* \.(?:css|js|map|jpe?g|gif|png)$ { }
  location / { 
      if (!-e $request_filename){ 
        rewrite ^(.*)$ /index.html?path= break; 
      }
  }

我检查了 nginx 的日志,我注意到它试图从另一个路径加载这些文件,错误是这个:

2017/12/13 22:47:55 [error] 14096#0: *50 open() "/usr/share/nginx/html/polyfills.22eec140b7d323c7e5ab.bundle.js" failed (2: No such file or di$rectory), client: xx.xxx.xxx.xx, server: subdomain.domain.com, request: "GET /styles.15b17d579c8773c5fdbd.bundle.css HTTP/1.1"

那么,为什么它尝试从 /usr/share/nginx/html/ 而不是我配置的根路径加载? 我应该修改什么才能加载 css 和 js 文件?谢谢

您的 location 块之一缺少 root,但由于它们共享相同的 root,因此应将其移至 server 上下文无论如何。

您不需要同时使用 try_filesif...rewrite。单独使用 try_files 可以实现相同的功能。

最后一个 location 块是不必要的,因为它使用与 location / 相同的 root

server {
    listen  80;
    server_name sibdomain.domain.com;
    root  /var/www/multiapp/dist;

    location ~* \.(?:css|js|map|jpe?g|gif|png)$ { }

    location / {
        index  index.html index.htm;
        try_files $uri $uri/ /index.html?path=$uri&$args;
    }

    error_page  500 502 503 504  /50x.html;
}

有关更多信息,请参阅 this document