通过 .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/

GD Star Rating
loading...
本文一共 248 个汉字, 你数一下对不对.
通过 .htaccess 设置静态资源缓存 来加速网站. (AMP 移动加速版本)
上一篇: 在系统负载高的时候收到邮件
下一篇: BASH 脚本匹配 IP 地址的 简单例子 (正则表达式)

扫描二维码,分享本文到微信朋友圈
ad3a2cb0ade4e1970a97b515248ce6cc 通过 .htaccess 设置静态资源缓存 来加速网站 LINUX 互联网 网站信息与统计

一条回应

评论