大网数据广告活动
服务器运维问答

Redirect http to https return double slashes

· 52CE 我爱测

My System is Centos 7 and Apache 2.4.6 I need to redirect http to https using Apache httpd.conf, I googled hundreds pages and I found some codes but this is good and not hard coded from DigitalOcean but it return double slash at …

问题原文

原帖链接 · Hady Shaltout · CC BY-SA 3.0

My System is Centos 7 and Apache 2.4.6

I need to redirect http to https using Apache httpd.conf, I googled hundreds pages and I found some codes but this is good and not hard coded from DigitalOcean but it return double slash at the end of URL and this is an image for the different redirect results

<VirtualHost IP:80>

   # https/http www -> https non-www

   RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
   RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

   # http non-www -> https non-www
   RewriteCond %{HTTPS} !=on
   RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

</VirtualHost>

<VirtualHost IP:443>

   # I removed this from 443 and the same result
   # https/http www -> https non-www
   RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
   RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

</VirtualHost>

已采纳解答

原帖链接 · Daniel Ferradal · CC BY-SA 3.0

That's because you are grabbing the first slash in (.*):

RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

This kind of regex is used in per-dir context, where the first slash is not used and does not apply, in virtualhost context first slash is present so you are capturing and adding it to the result with (.*).

So one the most typical and correct way to do it in virtualhost context is adding the slash manually before the capture group:

RewriteRule ^/(.*) https://%1/$1 [R=301,L]

Note: I removed the "$" because when you capture everything it is not necessary to specify "the end".

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

资料来源与适用范围

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

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

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