.htaccess如何在RewriteRule之前检查URI +文件扩展名是否存在

时间:2012-02-11 21:51:40

标签: .htaccess mod-rewrite

通过以下网址访问网页时:

/页面名

我们如何通过htaccess检查以下文件是否存在

/pagename.htm

然后加载index.php,如果没有?

以下是我正在使用的内容:

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

我尝试过这种变化,但没有运气:     RewriteCond%{REQUEST_URI}!/。htm -f

1 个答案:

答案 0 :(得分:4)

# If the URI is not .htm and doesn't have any additonal params, try .htm
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(?![^/]+\.htm)([^/]+)$ $1.htm [L,R=302]
# Adding the R flag causes the URI to be rewritten in the browser rather than just internally

# If the URI is .htm but it doesn't exist, pass to index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/\.]+\.htm)$ $1/no [L]

# Passes requested path as 'q' to index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/no/?$ index.php?q=$1 [L]

应该为你工作相当优雅。如果找不到该文件,它只是将其传递给index.php。您当然可以修改它使用的变量,我只是将'q'用于通用目的。

另外,请注意您可以将其压缩为一组RewriteConds。我已将它们扩展为注释目的。