使用PHP将WWW重定向到非WWW重定向 [英] WWW to non-WWW Redirect with PHP
问题描述
基本上,我想使用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['SERVER_NAME']
替换为$_SERVER['HTTP_HOST']
,它的工作方式应相同.
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重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!