问题原文
原帖链接 · Simon Hayter · CC BY-SA 3.0
I have noticed that one of my WordPress powered sites is experiencing double redirects when a user or bot attempts to visit a URL without HTTPS and a trailing slash.
In short:
http://example.com/contact-usredirects tohttps://www.example.com/contact-ushttps://www.example.com/contact-usredirects tohttps://www.example.com/contact-us/
My htaccess file looks like this:
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
What do I need to change to prevent these double redirects occurring?
社区高分解答
原帖链接 · Simon Hayter · CC BY-SA 3.0
I have managed to get this working by using a snippet provided by anubhava on Stack Overflow. If anyone spots a potential issue with this code or has a better and cleaner redirect then please don't hesitate to plonk your code as an answer.
RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^domain\.com$ [OR] RewriteCond %{HTTPS} off RewriteRule ^/?$ https://www.domain.com [R=301,L] RewriteCond %{HTTP_HOST} ^domain\.com$ [OR] RewriteCond %{HTTPS} off [OR] RewriteCond %{REQUEST_URI} !(/$|\.) RewriteRule ^(.+?)/?$ https://www.domain.com/$1/ [R=301,L]
So my .htaccess file now looks like this:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{HTTPS} off
RewriteRule ^/?$ https://www.example.com/ [R=301,L]
RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{HTTPS} off [OR]
RewriteCond %{REQUEST_URI} !(/$|\.)
RewriteRule ^(.+?)/?$ https://www.example.com/$1/ [R=301,L]
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
