1. 打开需要的模块
ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/proxy.load
ln -s /etc/apache2/mods-available/proxy_http.load /etc/apache2/mods-enabled/proxy_http.load
ln -s /etc/apache2/mods-available/cache.load /etc/apache2/mods-enabled/cache.load
ln -s /etc/apache2/mods-available/disk_cache.load /etc/apache2/mods-enabled/disk_cache.load
2.ReWrite 配置
我这里文章都是这样子的: http://www.example.com/Article.php?id=124323
我希望将它改为更加友好的方式: http://www.example.com/list/124323.html
RewriteEngine On
RewriteRule /articlelist/(.+)\.html$ /Article.php?id=$1 [L]
经过Rewrite配置后,重启确定Rewrite生效.
/etc/init.d/apache2 restart
3. 静态化
虽然这样子外人看起来像是静态化的了,但是每次访问都需要去查一次数据库,为了真正的实现静态化,我们通过mod_proxy和mod_disk_cache模块来实现。
用这个办法的好处是你不需要在前面再架设一个Squid之类的代理服务器,直接用apache2内置模块就可以实现了。性能也足够高,静态化后性能可以提高10倍,这还是在用简单sql查询的前提下,如果sql比较复杂,那性能的提高就更加明显了。
A. 先创建cache目录
mkdir -p /var/cache/apache2/proxy
chmod 777 /var/cache/apache2/proxy
chown -R www-data.www-data /var/cache/apache2/proxy
B. 修改php程序。 mod_cache遵循标准rfc协议,如果你的php输出里面没有过期设置,它将不会cache这个文件。
在php程序前面加入几行代码,注意一定要在输出正文前输出HTTP头
// 过期时间设置为一个月,如果你的文章不可能变,那将这个值设的更大些
$offset = 3600 * 24 * 30;
// 过期日期,当前时间+ 过期时间
$expire = “Expires: ” . gmdate(“D, d M Y H:i:s”, time() + $offset) . ” GMT”;
//输出HTTP 头
Header($expire);
C. 代理配置
www.example.com 是你的实际域名,请在/etc/hosts 文件写入IP解析,避免每次都去查询
127.0.0.1 www.example.com
<IfModule mod_proxy.c>
ProxyPass /staticlist/ http://www.example.com/list/
ProxyPassReverse /staticlist/ http://www.example.com/list/
<IfModule mod_disk_cache.c>
CacheRoot /var/cache/apache2/proxy
CacheEnable disk /staticlist/
CacheDirLevels 3
CacheDirLength 2
</IfModule>
</IfModule>
D. 重启apache 让其生效
/etc/init.d/apache2 restart
记得要将页面的链接改为新的 http://www.example.com/staticlist/1234.html
4. 注意事项:
如果生效了,会在 /var/cache/apache2/proxy 生成目录和文件,这个目录记得要有足够的空间。apache不会自动清理这个目录,你可以用htcacheclean 来清理。