强制 http/https:如何检测 https 以及重定向时发送哪个状态标头?
我编写了一个脚本来强制通过 http 或 https 访问网站的某些部分。我们希望用户被重定向到正常的 http 页面,以防他们意外登陆 https 版本,反之亦然。到目前为止,一切顺利,但我有两个问题要问你们。
切换协议时发送的正确状态标头是什么?在重定向之前,我目前在这两种情况下都使用此方法:
header('HTTP/1.1 301 永久移动');
检测我们是否使用 https 的首选方法是什么?
// if ($_SERVER['SERVER_PORT'] == 443) /* 编辑:好的,不是这个吗? */ if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) === 'on'))
还有别的事吗?两者都?
回复评论:
我们正在使用 Apache,但如果有一个通用的解决方案那就太好了。
我们不想使用
.htaccess
因为 https 所需的页面已被我们正在使用的 CMS 进行“标记”,并且这是其中的一部分。我们不想将 URL“硬编码”到文件中。
I've written a script to force certain sections of the site to be accessed via http or https. We want the user to be redirected to the normal http page in case they land on the https version by accident, and vice versa. So far, so good, but I have 2 questions for you guys.
What is the correct status header to send when switching protocol? I'm currently using this in both cases before redirecting:
header('HTTP/1.1 301 Moved Permanently');
What is the preferred way to detect if we're using https?
// if ($_SERVER['SERVER_PORT'] == 443) /* EDIT: OK, not this? */ if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) === 'on'))
Something else? Both?
Replies to comments:
We're using Apache, but if there's a universal solution that would great.
We don't want to use
.htaccess
because the https required pages are "flagged" as such by the CMS we're using, and that this is a part of. We don't want to "hard-code" the URLs into a file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
301
重定向是正确的方法。您无法在 HTTP 和 HTTPS 之间进行中途切换。该页面必须在客户端中重新加载。$_SERVER['HTTPS']
)是首选方法。只需确保您的网络服务器支持它即可。301
redirect is the proper method. You cannot switch between HTTP and HTTPS mid-stream. The page must be reloaded in the client.$_SERVER['HTTPS']
is the preferred method. Simply ensure that your web server supports it.