简体   繁体   中英

Load CSS and Js files with Nginx

I am trying to serve an Angular deployed site (I have a dist directory with the index.html file) in Nginx. In that directory I have:

  • index.html
  • js files
  • css files
  • assets

I don't have experience in Nginx, so I am trying to serve correctly this site. My configuration for that site is:

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

Right now the only file that is being loaded in the index, but the css and js file return 404. In apache this site was working correctly, I had this rule:

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]

And I used this site and they provided me this translation:

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

I checked the logs of nginx and I noticed that it's trying to load those files from another path, the error is this one:

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"

So, why its try to load from /usr/share/nginx/html/ and not the root path that I configured? What should I modify in order to be able to load the css and js files? thanks

You are missing a root for one of your location blocks, but as they all share the same root , it should be moved to the server context anyway.

You do not need both the try_files and the if...rewrite . The same functionality can be achieved using try_files alone.

The last location block is unnecessary as it uses the same root as location / .

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

See this document for more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM