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

1 .htaccess mod-rewrite

当通过这样的 URL 访问页面时:

/页名

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

/页面名称.htm

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

这是我正在使用的内容:

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*sco 5

# 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]
Run Code Online (Sandbox Code Playgroud)

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

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