【发布时间】:2010-10-15 10:47:35
【问题描述】:
我的服务器上有 html 静态文件。我希望访问规则为 -
- 如果用户访问http://example.com/test/他应该得到文件http://example.com/test.html的内容
- 如果用户访问http://example.com/test(没有尾部斜杠),他会被重定向到http://example.com/test/(运行规则1并获取文件test.html的内容)
- 规则 1 和 2 仅应在文件 test.html 存在时触发。
到目前为止,我有 -
Options All -Indexes -Multiviews
# Do not return details of server
ServerSignature Off
<IfModule mod_rewrite.c>
DirectorySlash Off
RewriteEngine On
RewriteBase /
# 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.
RewriteCond %{SCRIPT_FILENAME}/ -d
RewriteCond %{SCRIPT_FILENAME}.html !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [R=301,L]
# 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
RewriteRule ^(.*)/?$ $1.html [QSA,L]
</IfModule>
虽然它适用于http://example.com/test,但它对于http://example.com/test/ 失败(500 内部错误)
倒数第二行不应该处理斜杠吗?
[更新] 如果我使用 Gumbo 建议(.htaccess 后跟),我会得到 http://example.com/test 和 http://example.com/test/ 的 404(带有斜杠)
Options All -Indexes -Multiviews
# Do not return details of server
ServerSignature Off
ErrorDocument 404 /404.html
# Hide .htaccess
<Files ~ "^\.ht">
Order allow,deny
Deny from all
</Files>
<IfModule mod_rewrite.c>
DirectorySlash On
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^[^/]+$ %{REQUEST_URI}/ [L,R=301]
RewriteRule ^([^/]+)/$ $1.html [L]
</IfModule>
[更新 2] 我已经放弃了。下面的代码有效,但不是强制所有内容都以 / (http://example.com/test/) 结尾,而是删除尾部斜杠 (http://example.com/test)。从好的方面来说,它确保内容仅由一个 url 指向,从而保留 SEO。我现在要忍受它。
Options All -Indexes -Multiviews
# Do not return details of server
ServerSignature Off
ErrorDocument 404 /404.html
# Hide .htaccess
<Files ~ "^\.ht">
Order allow,deny
Deny from all
</Files>
<IfModule mod_rewrite.c>
DirectorySlash On
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$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 extesion.
RewriteRule [^/]$ %{REQUEST_URI}.html [QSA,L]
</IfModule>
【问题讨论】:
标签: .htaccess mod-rewrite apache2