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

How to make Apache’s mod_rewrite redirect over HTTPS by default?

· 52CE 我爱测

Let’s say I have a website that is available over HTTPS, e.g. https://example.com/foo . Consider the following .htaccess : RewriteBase / RewriteEngine On RewriteRule ^foo$ bar [R=301,L] Now, when I visit https://example.com/foo ,…

问题原文

原帖链接 · Mathias Bynens · CC BY-SA 3.0

Let’s say I have a website that is available over HTTPS, e.g. https://example.com/foo. Consider the following .htaccess:

RewriteBase /
RewriteEngine On
RewriteRule ^foo$ bar [R=301,L]

Now, when I visit https://example.com/foo, it redirects to http://example.com/bar, over HTTP instead of HTTPS.

How can I make it go to HTTPS other than using the full scheme + host for every RewriteRule with the R flag? That is, this would do what I’m after:

RewriteBase /
RewriteEngine On
RewriteRule ^foo$ https://example.com/bar [R=301,L]

However, my .htaccess file contains many such RewriteRules, and it feels like there should be a way to tell Apache/mod_rewrite “rewrite to https:// by default”. What I’m really looking for is a directive to tell Apache the site is using HTTPS, similar to how one can declare the host name through ServerName foo.ext. Is that possible?

I guess this is a similar question on Stack Overflow: How to convince Apache of the original client protocol

已采纳解答

原帖链接 · Mathias Bynens · CC BY-SA 3.0

ServerName accepts a scheme as well, e.g. ServerName https://example.com. Changing this in the configuration and restarting Apache did the trick.

From the documentation:

Sometimes, the server runs behind a device that processes SSL, such as a reverse proxy, load balancer or SSL offload appliance. When this is the case, specify the https:// scheme and the port number to which the clients connect in the ServerName directive to make sure that the server generates the correct self-referential URLs.

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

资料来源与适用范围

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

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

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