【问题标题】:Load CSS and Js files with Nginx使用 Nginx 加载 CSS 和 Js 文件
【发布时间】:2018-05-27 22:43:44
【问题描述】:

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

  • index.html
  • js 文件
  • css 文件
  • 资产

我没有使用 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=$1 break;
         }
    }

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

目前唯一加载到索引中的文件,但是 css 和 js 文件返回 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=$1 [NC,L,QSA]

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

# nginx configuration 
  location ~* \.(?:css|js|map|jpe?g|gif|png)$ { }
  location / { 
      if (!-e $request_filename){ 
        rewrite ^(.*)$ /index.html?path=$1 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 文件,我应该修改什么?谢谢

【问题讨论】:

  • 可以把root /var/www/multiapp/dist;放在服务器级别,去掉location ~* \.(?:css|js|map|jpe?g|gif|png)$ { }的位置

标签: nginx nginx-location


【解决方案1】:

您的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 了解更多信息。

【讨论】:

  • 您好,感谢您的回复。我试过了,它也更有条理。但是,在某种程度上,nginx 仍然在尝试从 /usr/share/nginx/html/ 加载 css 和 js 文件
  • 你重启nginx了吗?还使用“nginx -t”测试您的配置是否存在语法错误
猜你喜欢
  • 2015-10-08
  • 1970-01-01
  • 2015-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-22
相关资源
最近更新 更多