如何在 Heroku Cedar 堆栈上使用 .htaccess 重定向到 HTTPS [英] How to redirect to HTTPS with .htaccess on Heroku Cedar stack

查看:24
本文介绍了如何在 Heroku Cedar 堆栈上使用 .htaccess 重定向到 HTTPS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是云托管的新手...

I'm new to cloud hosting...

我正在开发作为Cedar"应用托管在 Heroku 上的 PHP 网络应用.Heroku 为其所有子域提供背负式"SSL,因此我可以很好地加载 https://myapp.herokuapp.com.但我也可以加载 http://myapp.herokuapp.com.我想通过将 http 请求重定向到 https 来强制使用 SSL.

I'm working on a PHP web app that's hosted on Heroku as a "Cedar" app. Heroku offers "piggy back" SSL to all their subdomains, so I can load https://myapp.herokuapp.com just fine. But I can also load http://myapp.herokuapp.com. I want to force SSL by redirecting http requests to https.

通常,这很容易.我只想使用 mod_rewrite 如下:

Normally, this would be easy. I would just use mod_rewrite as follows:

RewriteCond %{HTTPS} != on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

但这在 HEROKU 上不起作用!

在流量到达我的应用之前,SSL 似乎终止了上游.所以 %{HTTPS} 条件永远不会满足,结果是重定向循环.我也尝试了以下方法,但也没有奏效:

It appears that SSL terminates upstream, before the traffic ever hits my app. So the %{HTTPS} condition is never met, and the result is a redirect loop. I've also tried the following, which also didn't work:

RewriteCond %{SERVER_PORT} != 443 #<--also redirect loop
RewriteCond %{REQUEST_SCHEME} !https #<--also redirect loop

所以我的问题是如何在上游终止时检测/重定向到 HTTPS?

So my question is how can I detect/redirect-to HTTPS when it's terminated upstream?

推荐答案

在这个问题上花了一整天后,我想通了!!

After spending all day on this, I figured it out!!

这个问题得到了雄辩的总结此处.

The issue is eloquently summarized here.

底线:Heroku 设置自己的自定义标头以指示流量的原始方案(在 SSL 在负载均衡器处终止之前).

Bottom line: Heroku sets its own custom header to indicate the ORIGINAL scheme of the traffic (before SSL terminated at the load balancer).

所以这适用于 Heroku 上的 .htaccess 文件

So THIS works in an .htaccess file on Heroku

##Force SSL 

#Normal way (in case you need to deploy to NON-heroku)
RewriteCond %{HTTPS} !=on

#Heroku way
RewriteCond %{HTTP:X-Forwarded-Proto} !https 

#If neither above conditions are met, redirect to https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

秘诀在于HTTP:X-Forwarded-Proto.

希望这能帮助其他有同样问题的人!在撰写本文时,关于此的文档为零.

Hope this helps someone else having the same issues! At the time of writing this there is ZERO documentation on this.

这篇关于如何在 Heroku Cedar 堆栈上使用 .htaccess 重定向到 HTTPS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆