Truong Hua
Truong Hua

Reputation: 23

Config caching css/js files at Nginx

I'm using nginx host by Ubuntu 14.04

My config file :

  server {

    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    # Make site accessible from http://localhost/
    server_name testing.com;



location /site/admin/ {
    alias /usr/share/nginx/html/site/admin/src/;
}

location ~ \.(css|js)$ {
     expires 1y;
     access_log off;
     add_header Cache-Control "public";
}

I've got some errors

[error] 29224#0: *10047 open()     "/usr/share/nginx/html/site/admin/assets/js/jquery.nestable.js" failed (2: No such file or directory) 

Actually that file is located :

 /usr/share/nginx/html/site/admin/src/assets/js/jquery.nestable.js

How can i set my config file?

Upvotes: 2

Views: 4976

Answers (1)

Richard Smith
Richard Smith

Reputation: 49812

Your location ~ \.(css|js)$ block inherits root /usr/share/nginx/html from the server block.

Also, regular expression location blocks take precedence over prefix location blocks - see this document for details.

You can force your location /site/admin/ block to override regular expression location blocks at the same level by using the ^~ modifier:

location ^~ /site/admin/ {
    alias /usr/share/nginx/html/site/admin/src/;
}

The above location block is a prefix location (and not a regular expression location block). See this document for details.

Of course, this also means that URIs beginning with /site/admin/ and ending with .css or .js will no longer have their caching parameters changed. This can be fixed by adding a nested location block, as follows:

location ^~ /site/admin/ {
    alias /usr/share/nginx/html/site/admin/src/;

    location ~ \.(css|js)$ {
        expires 1y;
        access_log off;
        add_header Cache-Control "public";
    }
}

Upvotes: 3

Related Questions