PHP https url 转发
好的,所以我需要我的网站自动将所有请求转发到服务器,将 http 转换为 https。我使用 php 没有遇到任何实际问题,但现在 godaddy 告诉我,我需要改变我这样做的方式。我的代码正确吗?我应该改变我的做法吗?什么方法更好?预先感谢您的帮助!
<?php
if ($_SERVER['SERVER_PORT']!=443)
{
$url = "https://". $_SERVER['SERVER_NAME'] . ":443".$_SERVER['REQUEST_URI'];
header("Location: $url");
}
?>
Ok so I need my site to automatticly forward all requests to the server for http to https. I was using php with no real problems but now godaddy is telling me that I need to change the way i am doing this. Is my code correct, should i change how im doing this, what method is better? Thanks in advance for the help!
<?php
if ($_SERVER['SERVER_PORT']!=443)
{
$url = "https://". $_SERVER['SERVER_NAME'] . ":443".$_SERVER['REQUEST_URI'];
header("Location: $url");
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您不需要包含端口号... https 的默认端口已经是 443。如果您在其他端口上运行 https 服务,则只需要明确的端口号。另外,为什么要重复重定向?您有 2 个 if() 块执行完全相同的操作。
但是,仅测试端口 443 是不够的。您可以在任何端口上运行任何您想要的服务。只是 HTTPS 通常位于 443 上。但没有任何规定必须如此。
$_SERVER['HTTPS']
会明确告诉您 HTTPS 是否正在使用。You don't need to include the port number... https' default port is 443 already. You'd only need an explicit port number if you're running an https service on some OTHER port. As well, why the duplicate redirect? You've got 2 if() blocks doing the exact same thing.
However, just testing for port 443 is not sufficient. You can run ANY service you want on any port. It's just that HTTPS usually is on 443. But nothing says it HAS to be. There's
$_SERVER['HTTPS']
which explicity tells if you if HTTPS is in use or not.更好的方法是使用 .htaccess 和 mod_rewrite 进行重定向。
此处对此进行了更详细的解释。
A better method would be to use .htaccess and mod_rewrite to do the redirect.
This is explained in more detail here.
我会使用此处描述的内容:
在此处输入链接描述
我不想依赖用于端口 443。有人可以将正常流量配置为 443 或使用另一个端口进行 https(两种情况都很罕见)。
此外,由于它是默认值,因此您可以省略“:443”...
I would use something as described here:
enter link description here
I would not like to rely for port 443. Someone can configure normal traffic towards 443 or use another port for https (both rare).
Additionally since it is the default, you can ommit the ":443"...
您可以使用 htaccess 来执行此操作:
希望有帮助
You could use htaccess for doing this:
Hope it helps
我在 .htaccess 文件中使用此代码,效果很好:
I am using this code in my .htaccess file which works great: