在 Nginx 配置缓存 css/js 个文件

Config caching css/js files at Nginx

我在 Ubuntu 14.04

使用 nginx 主机

我的配置文件:

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

我有一些错误

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

实际上该文件位于:

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

如何设置我的配置文件?

您的 location ~ \.(css|js)$ 块从服务器块继承 root /usr/share/nginx/html

此外,正则表达式位置块优先于前缀位置块 - 有关详细信息,请参阅 this document

您可以使用 ^~ 修饰符强制您的 location /site/admin/ 块覆盖同一级别的正则表达式位置块:

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

上面的位置块是前缀位置(而不是正则表达式位置块)。有关详细信息,请参阅 this document

当然,这也意味着以 /site/admin/ 开头并以 .css.js 结尾的 URI 将不再更改其缓存参数。这可以通过添加嵌套位置块来解决,如下所示:

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

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