小赖子的英国生活和资讯

通过 .htaccess 设置静态资源缓存 来加速网站

阅读 桌面完整版

静态资源是可以通过 缓存设置来加速读取的. 设置方法很简单 但首先你得在 apache2 服务器里把 相关的 模块 开启了 i.e. header.

1
a2enmod headers
a2enmod headers

这个模块是用于设置静态资源缓存的 如果没开启 你将会获得 500 服务器内部错误.

Module headers already enabled

然后 在每个网站的 根目录 .htaccess 文件里 加入 以下内容 并保证 apache2 对于 mod_rewrite 的设置是 Override All 这样子目录的 设置会从根目录下继承.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 # 1 Month for all your static assets 一个月
 <FilesMatch ".(ico|pdf|bmp|vbs|flv|jpg|jpeg|png|gif|js|css|swf)$">
 Header set Cache-Control "max-age=2592000, public"
 </FilesMatch>
 
 # 1 DAYS for rss feeds and robots  一天
 <FilesMatch ".(xml|txt)$">
 Header set Cache-Control "max-age=86400, public, must-revalidate>
 </FilesMatch>
  
 # 8 HOURS for your real articles files 8小时
 <FilesMatch ".(html|htm)$">
 Header set Cache-Control "max-age=28800, must-revalidate>
 </FilesMatch>
 # 1 Month for all your static assets 一个月
 <FilesMatch ".(ico|pdf|bmp|vbs|flv|jpg|jpeg|png|gif|js|css|swf)$">
 Header set Cache-Control "max-age=2592000, public"
 </FilesMatch>
 
 # 1 DAYS for rss feeds and robots  一天
 <FilesMatch ".(xml|txt)$">
 Header set Cache-Control "max-age=86400, public, must-revalidate>
 </FilesMatch>
  
 # 8 HOURS for your real articles files 8小时
 <FilesMatch ".(html|htm)$">
 Header set Cache-Control "max-age=28800, must-revalidate>
 </FilesMatch>

过期时间 是用秒来记录的. 这样 APACHE 服务器就会告诉你的浏览器 资源还没过期不需要重新下载 而是尽可能的去本地找之前已经缓存好的, 这样一是减少服务器负担 另一是加快页面读取时间.

最后 保存之后 记得要重启服务器.

1
sudo /etc/init.d/apache2 restart
sudo /etc/init.d/apache2 restart

或者:

1
sudo service apache2 restart
sudo service apache2 restart

效果真的非常好!

英文: https://helloacm.com/speed-up-website-by-caching-static-resources-using-apache2-cache-control-htaccess/

强烈推荐

微信公众号: 小赖子的英国生活和资讯 JustYYUK

阅读 桌面完整版
Exit mobile version