You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何防止.htaccess缓存留存CodeIgniter会话数据

针对CodeIgniter图片密集型网站的.htaccess缓存优化方案

Hey there! Let's walk through the .htaccess caching setup you've started for your CodeIgniter site that's heavy on image content. Here's a polished, complete version of the rules along with clear breakdowns to make sure it's working effectively for your needs:

完整的Expires缓存规则

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
# 图片资源:长期缓存(1年),这类资源极少变动
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType image/webp "access 1 year"
ExpiresByType image/svg+xml "access 1 year"

# 样式与脚本:中等缓存(1个月),可能会有版本更新
ExpiresByType text/css "access 1 month"
ExpiresByType application/javascript "access 1 month"
ExpiresByType text/javascript "access 1 month"

# 文档与HTML:注意HTML如果是CodeIgniter动态生成的,可调整周期
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"

# 字体资源:长期缓存(1年)
ExpiresByType application/x-font-woff "access 1 year"
ExpiresByType application/x-font-woff2 "access 1 year"
ExpiresByType font/ttf "access 1 year"
ExpiresByType font/otf "access 1 year"
</IfModule>
## EXPIRES CACHING END ##

关键规则说明

  • <IfModule mod_expires.c>:这段规则仅在Apache服务器启用了mod_expires模块时生效,避免服务器因模块未开启而报错。
  • ExpiresActive On:全局开启过期缓存功能。
  • 图片/字体类:设置1年缓存周期,因为这类资源发布后几乎不会修改,长期缓存能大幅降低服务器请求量和用户加载时间。
  • CSS/JS类:设置1个月缓存,平衡缓存收益和更新灵活性——如果你的样式/脚本更新频繁,可以缩短到1周。
  • HTML/PDF类:注意!如果你的CodeIgniter产品页面是动态生成的(比如包含实时库存、用户专属内容),建议把text/html的缓存周期改成"access plus 0 seconds"或者直接移除这条规则,避免用户看到过期的动态内容。

额外注意事项

  • 确认你的Apache服务器已启用mod_expires:可以通过查看httpd.conf或联系主机商确认,模块启用后需要重启服务器生效。
  • 资源更新时的缓存刷新:如果需要强制用户加载最新的资源(比如更新了图片或CSS),建议给资源文件名加上版本号(例如product-image-v2.jpg、style-v3.css),这样浏览器会识别为新资源,自动绕过缓存请求最新版本。

内容的提问来源于stack exchange,提问作者Zee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:10:51