RewriteRule ^([^/]+)/$ $1.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.html
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
您现有的规则都期望(或强制)在您的所有URL上使用尾随斜杠.因此,如果规范的URL(以及您要链接的URL)不包括尾随斜杠,则所有这些规则基本上都需要颠倒.然而,这里还有其他问题(例如,第一个规则是unconditionally重写附加.html
扩展的请求,这在下一个规则with A条件中重复).
请try 以下操作:
RewriteEngine On
# (OPTIONAL) Remove trailing slash if it happens to be on the request
# Exclude physical directories (which must end in a slash)
RewriteRule %{REQUEST_FILENAME} !-d
RewriteRule (.+)/$ /$1 [R=301,L]
# Rewrite request to corresponding ".html" file if it exists
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule ^([^.]+)$ $1.html [L]
您的原始指令只处理具有一个或两个路径深度的URL(例如,/foo/
或/foo/bar/
).上面的第二个规则处理任何路径深度(如果需要).例如./foo
、/foo/bar
、/foo/bar/baz
等(无尾部斜杠).
作为优化,我有assumed个需要重写的URL不包含点(否则用来分隔文件扩展名).
请注意,RewriteRule
pattern(第一个参数)只与URL路径(而不是查询字符串)匹配.如果初始请求上有任何查询字符串,则默认情况下只传递该字符串.(对于重写和客户端JS,查询字符串在初始请求中可用,应该像以前一样进行解析.)
正因为如此,我在网站上的照片被打破了.
如果您使用的是图像的相对URL,则会发生这种情况.您真的应该使用根相对URL(以斜杠开头)或绝对URL来解决此问题.另见: