【发布时间】:2012-10-25 11:17:06
【问题描述】:
我有一个具有以下文件/文件夹结构的静态站点:
- index.html
- /foobar/
- index.html
- bob.html
- alice.html
我想实现以下目标:
- 删除所有
.html扩展。 ✔ 有效 - 删除
index.html(分别为index)。 ✔ 有效 - 我希望文件结尾没有斜杠。 ✔ 有效
- 如果有人添加了斜杠,则重定向到不带斜杠的 URL。 ✘ 不起作用
- 我希望“文件夹”(实际上是文件夹内的
index.html文件)结束时没有斜杠。 ✘ 不起作用- 如果有人添加了斜杠,则重定向到不带斜杠的 URL。 ✘ 不起作用
所以以下 URL 应该可以工作:
-
example.com/(其实是:/index.html) -
example.com/foobar(其实是:/foobar/index.html) -
example.com/foobar/bob(其实是:/foobar/bob.html) -
example.com/foobar/alice(其实是:/foobar/alice.html)
以下请求应重定向 (301):
-
example.com/foobar/重定向到:example.com/foobar) -
example.com/foobar/bob/重定向到:example.com/foobar/bob) -
example.com/foobar/alice/重定向到:example.com/foobar/alice)
我看到当文件/foobar.html存在时这会产生问题:当有人访问/foobar时,不清楚是请求目录还是文件。不过,我会确保这永远不会发生。
目前,我有这个.htaccess:
# Turn MultiViews off. (MultiViews on causes /abc to go to /abc.ext.)
Options +FollowSymLinks -MultiViews
# It stops DirectorySlash from being processed if mod_rewrite isn't.
<IfModule mod_rewrite.c>
# Disable mod_dir adding missing trailing slashes to directory requests.
DirectorySlash Off
RewriteEngine On
# If it's a request to index(.html)
RewriteCond %{THE_REQUEST} \ /(.+/)?index(\.html)?(\?.*)?\ [NC]
# Remove it.
RewriteRule ^(.+/)?index(\.html)?$ /%1 [R=301,L]
# Add missing trailing slashes to directories if a matching .html does not exist.
# If it's a request to a directory.
RewriteCond %{SCRIPT_FILENAME}/ -d
# And a HTML file does not (!) exist.
RewriteCond %{SCRIPT_FILENAME}.html !-f
# And there is not trailing slash redirect to add it.
RewriteRule [^/]$ %{REQUEST_URI}/ [R=301,L]
# Remove HTML extensions.
# If it's a request from a browser, not an internal request by Apache/mod_rewrite.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
# And the request has a HTML extension. Redirect to remove it.
RewriteRule ^(.+)\.html$ /$1 [R=301,L]
# If the request exists with a .html extension.
RewriteCond %{SCRIPT_FILENAME}.html -f
# And there is no trailing slash, rewrite to add the .html extension.
RewriteRule [^/]$ %{REQUEST_URI}.html [QSA,L]
</IfModule>
我必须在我的.htaccess 中更改/删除/添加什么?我不太明白。我试图删除注释“如果匹配的 .html 不存在,则在目录中添加缺少的尾部斜杠”的块,但这没有帮助。
【问题讨论】:
-
FWIW,我在 Code Review 上询问了可能的改进:codereview.stackexchange.com/q/18440/16414
标签: .htaccess mod-rewrite url-rewriting trailing-slash