大网数据广告活动
网站运营与故障问答

WordPress HTTP to HTTPS without trailing slash results in double redirect

· 52CE 我爱测

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-us redirects to https://ww…

问题原文

原帖链接 · 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-us redirects to https://www.example.com/contact-us
  • https://www.example.com/contact-us redirects to https://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.

SOURCE

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>

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2017-02-16)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。