.htaccess - 用 https 和尾随 / 一步重写会产生意想不到的后果

.htaccess - rewrite with https and trailing / in one step has unintended conseqences

我最近使用 cloudflare 向我的网站添加了 ssl 证书。我在 .htaccess 中添加了一些行以默认使用 https。查看 google 页面速度洞察,我注意到当使用 http 访问我网站的子目录时,发生了三个重定向。例如,访问 http://markfisher.photo/galleries.

时会出现以下重定向链
  1. http://markfisher.photo/galleries
  2. https:://markfisher.photo/galleries(抱歉,没有足够的代表 >2 links。双冒号将打破 link)
  3. http://markfisher.photo/galleries/
  4. https://markfisher.photo/galleries/

我通过将 .htaccess 中的相关行修改为

来修复此问题(即在一个步骤中合并 https 和尾部斜线)
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTP_HOST} ^markfisher.photo$ [OR]
RewriteCond %{HTTP_HOST} ^www.markfisher.photo$
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}\/ [L,R]

与之前相比的唯一变化是在底线末尾添加 /。这适用于我网站的子目录,但是当使用 http http:://markfisher.photo 访问根目录时,它会被重定向到 https:://markfisher.photo//。这工作正常但看起来很难看。我无法弄清楚如何阻止双斜杠的出现。我猜它与我的主机使用的全局 .htaccess 文件有关,但我不知道该文件可能包含什么,所以我正在努力解决它。

此外,如果有人能告诉我如何在没有任何额外重定向的情况下将 www 放入其中,那就太好了。

以下有效。我分为 2 种情况 - 一种是尾部斜杠不存在且需要重写,另一种是它存在的位置,因此不需要额外的斜杠。

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTP_HOST} ^markfisher.photo$ [OR]
RewriteCond %{HTTP_HOST} ^www.markfisher.photo$
RewriteCond %{REQUEST_URI} !^/$
RewriteCond %{REQUEST_URI} !^/.*/$
RewriteRule ^ https://www.markfisher.photo%{REQUEST_URI}\/ [R=301]


RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTP_HOST} ^markfisher.photo$ [OR]
RewriteCond %{HTTP_HOST} ^www.markfisher.photo$
RewriteCond %{REQUEST_URI} ^.*/$
RewriteRule ^ https://www.markfisher.photo%{REQUEST_URI} [R=301]