2013-10-22 153 views
13

我在定义缓存我的静态文件的规则时遇到了一些问题。我发现这个解决方案:NGINX缓存静态文件

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

这实际上看起来像我所需要的。问题是,如果我把这个代码包含到我的NGINX.conf中,那么就不会再有静态文件了,我的网站也是空白的。任何想法/提示可能会导致这种结果?也许我必须补充说,静态文件分布在不同的目录中:/。我NGINX配置文件看起来是这样的:

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

将是很好,如果有人可以帮助我这个或点我在正确的方向。

干杯, Szop

+0

你不介意,你发布的完整配置? – alfredocambera

回答

28

把这个您的其他位置前:

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

这应该工作。

你也可以使用此:

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

在这种情况下,如何清除缓存?它会像重新启动nginx一样简单吗? – hamstar

+2

本示例不是服务器端缓存,它管理浏览器缓存。如果我们更新服务器上的静态文件,它是否会立即为客户端更新新文件,或者我们必须等到它过期,才能清除浏览器缓存:Shift + F5/ctrl + F5 –

+0

。 – nXqd