分组文件扩展名以重写 URL 的 [.htaccess]

Grouping file extensions for re-writing URL's [.htaccess]

我怎样才能将这两个组合在一起?是不是像“.(html|php)$” - 请提供代码。

请注意,答案应该适用于所有文件扩展名:您对删除每个文件扩展名有何想法?对使用的代码发表评论 - 因为很难找到。

RewriteCond %{THE_REQUEST} ^GET\ (.*)\.html\ HTTP
RewriteRule (.*)\.html$  [R=301]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) \.html [L]

RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$  [R=301]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) \.php [L]

看来您几乎用

回答了您自己的问题

is it like ".(html|php)$"

你只需要尝试一下。看看这是否适合您对 html and php 个文件进行分组。

RewriteCond %{THE_REQUEST} ^GET\ (.*)\.(php|html)\ HTTP
RewriteRule ^ %1 [R=301,L]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^/]+)/?$ .php [L]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^/]+)/?$ .html [L]

还有另一种可能的解决方案。就是不使用上面的代码而使用MultiViews。下面一行代码。

Options +FollowSymLinks +MultiViews

很遗憾,这是不可能的。

RewriteCondTestString 部分只能包含纯字符串,并允许服务器变量(例如 HTTP_REFERER)和反向引用(例如 </code> 和 <code>%1)。

因此,您不能在 TestString 中包含表达式 - 只有 CondPatternRewriteCond 的第二部分) 允许表达式。

您能做的最好的事情是使用表达式去除不需要的扩展名,然后,对于您去除的每个扩展名,确定它是否存在并相应地重写 - 就像这样:

RewriteEngine on

# Step 1: Strip out extensions you don't want for files that actually exist

RewriteCond %{THE_REQUEST} ^GET\ (.*)\.(html|php)\ HTTP
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ %1 [R=301,L]

# Step 2: For each extension stripped, rewrite for existing files

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule (.*) .html [L]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule (.*) .php [L]

旁注: 如果 Apache 在 .htaccess 文件中实现某种循环,那就太好了——这将有助于简化这种方法。不幸的是,情况并非如此,因此以上几乎是最好的方法。