Skip to main content
 首页 » 编程设计

NGINX 缓存静态文件

2024年11月24日43jiqing9006

我在定义缓存静态文件的规则时遇到了一些麻烦。我找到了这个解决方案:

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/; 
  } 
} 
如果有人能帮我解决这个问题或为我指明正确的方向,那就太好了。

请您参考如下方法:

把它放在你的其他位置块之前:

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