开发者

Using mod_rewrite to view cached version from usual URL

开发者 https://www.devze.com 2023-02-23 03:36 出处:网络
My PHP site generates static html versions of dynamic db driven code and stores them in a folder called cache.

My PHP site generates static html versions of dynamic db driven code and stores them in a folder called cache.

This means that when you visit say, /about-us/, the request is routed through index.php?page=about-us, and produces a file called /cache/about-us.html.

If that file exists, the PHP includes it, then exits. This seems a waste of time, why not just get apache to serve up /cache/about-us.html when /about-us/ is requested, but only if it exists.

My current mod_rewrite section 开发者_开发问答just includes this so far:

RewriteRule ^([A-Za-z0-9-_/\.]+)\/$ /?page=$1 [L]

Which writes any /foo_bar/ request to index.php?page=foo_bar. What can I put before this to request my cached version if it exists?


First send everything to the /cache/ folder

RewriteRule ^([A-Za-z0-9-_/\.]+)/$ /cache/$1

Then, check if it's not found, and reroute

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/cache/([A-Za-z0-9-_/\.]+)$ /page?=$1 [L]

Depending on how your server is set up you might have to change the paths a bit (I'd recommend using absolute ones). Also note that this will also apply to images that match the RewriteRule

I'm not sure wether you'll see any significant performance increase with this - just including a static file doesn't take that long (if you don't hit a database). Also, if you have APC you could cache the files in-memory.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号