通过附加.html后缀重写URL

时间:2015-09-04 11:26:24

标签: apache .htaccess mod-rewrite apache2.4

我正在尝试将mod_rewrite与Apache 2.4一起使用后缀.html来请求URI。

应该重写的URI非常简单,并采用以下形式:

http://host.domain/page/

上述内容需要重写为http://host.domain/page.html。唯一的限制是重写逻辑必须忽略引用实际文件或目录的URI。

到目前为止,如果有没有斜杠,我提出的重写代码段工作正常,但是如果存在,那么Apache会发出404并发出以下错误消息:

The requested URL /redirect:/about.html was not found on this server.

(上述情况发生在URI为http://localhost/about/

有人可以帮我调试吗?为什么Apache前置/redirect:

这是一个非常简单的代码片段,可以重现这些症状:

RewriteEngine on

RewriteBase /

RewriteRule ^(.+[^/])/$ /$1 [C]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^$
RewriteRule (.*) /$1.html [L,R=301] # Tried without R=301 too

# This doesn't work either.
# RewriteRule ^about/$ /about.html [L,R=301]

1 个答案:

答案 0 :(得分:2)

您可以使用:

RewriteEngine on
RewriteBase /

# strip trailing slash from non-directoies
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/$ /$1 [L,R=301]

# make sure corresponding html file exists
RewriteCond %{DOCUMENT_ROOT}/$1\.html -f
RewriteRule ^(.+?)/?$ $1.html [L]