Apache/Nginx url rewrite trick: 目录下 index.html 不存在时重写

June 26th, 2010 no comment

最近做一个被动式静态页生成功能,即是在请求发生时若静态文件不存在,便将请求重写到PHP生成内容,再在输出前将内容存入到对应路径,下次请求时服务器便直接输出静态页,不用经过PHP。生成部分相当简单,没费什么周折。

Apache 重写规则设定如下:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

当请求的URL为 /products/ipad_16g.html 时,一切行为都很符合期望。

但我同时也期望请求URL为 /products 时,可以看到产品的列表,实际上当 /products 目录存在而默认文档 index.html 不存在时便会报错。好在 Apache Rewrite 支持逻辑操作符,解决起来也方便,加上对 index.html 的判断便可完美解决:

RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME}/index.html !-f
RewriteRule . /index.php [L]

Nginx rewrite 不支持逻辑操作符,利用 break 可达到同一效果:

if (-f $request_filename) {
break;
}
if (-f $request_filename/index.html) {
break;
}
rewrite ^ /index.php last;

Leave A Comment

All fields marked with "*" are required.





Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>