Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

NGINX cache static files

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 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.

question from:https://stackoverflow.com/questions/19515132/nginx-cache-static-files

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...