问题描述
我想用 PHP 将所有 www.domain.com 请求重定向到 domain.com,基本上:
I want to redirect all www.domain.com requests to domain.com with PHP, basically:
if (substr($_SERVER['SERVER_NAME'], 0, 4) === 'www.')
{
header('Location: http://' . substr($_SERVER['SERVER_NAME'], 4)); exit();
}
但是我确实想像 SO 一样维护请求的 URL,例如:
However I do want to maintain the requested URL like in SO, for e.g.:
http://www.stackoverflow.com/questions/tagged/php?foo=bar
应该重定向到:
http://stackoverflow.com/questions/tagged/php?foo=bar
我不想依赖 .htaccess
解决方案,而且我不确定我必须使用哪些 $_SERVER
变量来实现这一点.此外,保留 HTTPS 协议将是一个加分项.
I don't want to rely on .htaccess
solutions, and I'm unsure which $_SERVER
vars I'd have to use to make this happen. Also, preserving the HTTPS protocol would be a plus.
我该怎么做?
推荐答案
$pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else
{
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
header('Location: '. $pageURL);
会将用户重定向到完全相同的页面 www.完好无损的.
Would redirect the user to the exact same page, www. intact.
所以,去掉www.,我们只替换一行:
So, to get rid of the www. , we just replace one line:
$pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= substr($_SERVER['SERVER_NAME'], 4).":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else
{
$pageURL .= substr($_SERVER['SERVER_NAME'], 4).$_SERVER["REQUEST_URI"];
}
return $pageURL;
这应该可行.
顺便说一句,这是 Google 推荐的方法,因为它保持 https://
完整,以及端口等,如果您确实使用它们.
By the way, this is the method that is recommended by Google, as it keeps https://
intact, along with ports and such if you do use them.
正如 Gumbo 指出的,他使用 $_SERVER['HTTP_HOST']
因为它来自标头而不是服务器,因此 $_SERVER['SERVER_*']
不那么可靠.你可以用 $_SERVER['HTTP_HOST']
替换 some$_SERVER['SERVER_NAME']
,它应该以同样的方式工作.
As Gumbo pointed out, he uses $_SERVER['HTTP_HOST']
as it comes from the headers instead of the server, thus $_SERVER['SERVER_*']
is not as reliable. You could replace some$_SERVER['SERVER_NAME']
with $_SERVER['HTTP_HOST']
, and it should work the same way.
这篇关于使用 PHP 将 WWW 重定向到非 WWW的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!