我对Apache mod_rewrite规则有一些问题。每当我尝试转到https://example.com// (请参阅末尾的双斜杠),它就会重定向到301页,但是它正在添加目录的位置,即https://example.com/var/www/my-domain.com/html,这是不可取的。
这是我的.htaccess文件:
ErrorDocument 404 /views/pages/404.php
RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
RewriteCond %{THE_REQUEST} \s/+(.*?)/+(/\S+) [NC]
RewriteRule ^(.*) [L,R=404]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/{2,} [NC]
RewriteRule ^(.*) $1 [R=301,L]
RewriteRule ^contact-us/?$ views/pages/contact.php [NC,L]当我去https://example.com//contact-us的时候也会发生同样的事情。
https://example.com/contact-us//很好地重定向到https://example.com/contact-us,https://example.com//contact-uss很好地重定向到404页面。
如果需要进一步的信息,请告诉我。
发布于 2018-11-11 02:50:18
RewriteCond %{THE_REQUEST} ^A{3,}s/{2,} NC RewriteRule ^(.*) $1 R=301,L
您在替换时缺少了斜杠前缀。这将导致相对路径替换(因为$1反向引用不包含斜杠前缀),mod_rewrite将目录前缀(即./var/www/example.com/html)。这将导致你所看到的畸形的重定向。RewriteRule应该写成:
RewriteRule (.*) /$1 [R=301,L](这里没有必要在^模式上使用RewriteRule锚点。)
然而,以下重定向也是无效的:
RewriteCond %{THE_REQUEST} /+(.*?)/+(/\S+) NC RewriteRule ^(.*) L,R=404
你完全忽略了替代论点。[L,R=404]将被视为替代字符串(而不是预期的标志)。这还会导致格式错误的重写/重定向。RewriteRule应该写成:
RewriteRule (.*) - [R=404]注意,- (单连字符)用作替换参数(稍后被忽略)。当指定非3xx响应代码时,会隐含L标志。
但是,我很好奇您在这里试图做什么,因为您似乎在“接受”一个指令中的多个斜杠(通过减少它们),然后在另一个指令中拒绝多个斜杠(使用404)?为什么不减少在URL路径中出现的多个斜杠的所有序列?
例如,替换以下代码(修改后的代码):
# Remove trailing slash from URL (except files and directories)
# >>> Why files? Files don't normally have trailing slashes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Reject multiple slashes later in the URL or 3+ slashes at the start of the URL
RewriteCond %{THE_REQUEST} \s/+(.*?)/+(/\S+) [NC]
RewriteRule (.*) - [R=404]
# Reduce multiple slashes at the start of the URL
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/{2,} [NC]
RewriteRule (.*) /$1 [R=301,L]使用以下内容(取决于需求):
# Reduce sequences of multiple slashes to a single slash in the URL-path
# NB: This won't work to reduce slashes in the query string (if that is an issue)
RewriteCond %{THE_REQUEST} //+
RewriteRule (.*) /$1 [R=302,L]
# Remove trailing slash from URL (except directories)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=302,L]请注意,我已经反转了指令,以便在删除最后的尾斜杠之前减少斜杠。
使用302进行测试,以避免缓存问题。并在测试前清除浏览器缓存。
更新:如果双斜杠可能(合法地)发生在的查询字符串部分,那么上面的结果将导致重定向循环,因为条件检查URL中任何地方的多个斜杠(包括查询字符串),而RewriteRule只减少URL -路径中的多个斜杠。如果需要允许查询字符串中的多个斜杠,那么将CondPattern从//+更改为\s[^?]*//+,以便只专门检查URL路径,而不是整个URL。换言之:
RewriteCond %{THE_REQUEST} \s[^?]*//+
RewriteRule (.*) /$1 [R=302,L]https://stackoverflow.com/questions/53236444
复制相似问题