NGINX cache static files

后端 未结 2 538
-上瘾入骨i
-上瘾入骨i 2020-12-23 20:23

I\'m having some trouble defining a rule to cache my static files. I\'ve found this solution:

location ~* \\.(ico|js|css|png|gif|jpe?g)$ {
  expires 7d;
}


        
相关标签:
2条回答
  • 2020-12-23 21:05

    Put this before the server section in nginx config file as shown bellow:

    . . .
    # Expires map
    map $sent_http_content_type $expires {
        default                    off;
        text/html                  epoch;
        text/css                   max;
        application/javascript     max;
        ~image/                    max;
    }
    
    server {
       listen 80 default_server;
       listen [::]:80 default_server;
    
       expires $expires;
    . . .
    

    the ~image will handle all kind of images ( instead of hardcoding them )

    for further informations on how to handle nginx caching see link

    0 讨论(0)
  • 2020-12-23 21:20

    Put this before your other location block:

    location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
        expires 30d;
        add_header Vary Accept-Encoding;
        access_log off;
    }
    

    That should work.

    You could also use this:

    ## All static files will be served directly.
    location ~* ^.+\.(?:css|cur|js|jpe?g|gif|htc|ico|png|html|xml|otf|ttf|eot|woff|woff2|svg)$ {
        access_log off;
        expires 30d;
        add_header Cache-Control public;
    
        ## No need to bleed constant updates. Send the all shebang in one
        ## fell swoop.
        tcp_nodelay off;
    
        ## Set the OS file cache.
        open_file_cache max=3000 inactive=120s;
        open_file_cache_valid 45s;
        open_file_cache_min_uses 2;
        open_file_cache_errors off;
    }
    
    0 讨论(0)
提交回复
热议问题