NGINX cache static files

2019-03-09 15:11发布

问题:

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

which actually looks like what I need. The problem is, if I include this code into my into the NGINX.conf, no static files are delivered anymore and my site is blank. Any ideas/hints what might cause this result? Maybe I have to add, that the static files are distributed in different directories :/. My NGINX config file looks like this:

server {
  server_name               bla.domain.com;

  listen                    80;
  root                      /var/repo/;

  location / {
    default_type            text/html;
    index                   index.html;

    if ($request_method !~ ^(GET)$ ) {
      return 444;
    }

    if ($http_user_agent ~* LWP::Simple|BBBike|wget) {
      return 403;
    }

    if ( $http_referer ~* (babes|forsale|girl|jewelry|love|nudit|organic|poker|porn|sex|teen) ) {
      return 403;
    }
  }

  location /bf/football/ {
    alias   /var/repos/f20;
  }

  location /bf/f20/ {
    alias   /var/repo/f20;
  }

  location /bf/zoo/ {
    alias   /var/repo/zoo/;
  }

  location /kbloader/ {
    alias   /var/repo/kbloader/;
  }
}

Would be nice if someone could help me out with this or point me in the right direction.

Cheers, Szop

回答1:

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|svg)$ {
    access_log off;
    expires 30d;

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


回答2:

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



标签: nginx static