我想用 PHP 将所有 www.domain 请求重定向到 domain,基本上:
I want to redirect all www.domain requests to domain with PHP, basically:
if (substr($_SERVER['SERVER_NAME'], 0, 4) === 'www.') { header('Location: ' . substr($_SERVER['SERVER_NAME'], 4)); exit(); }但是我确实想像 SO 一样维护请求的 URL,例如:
However I do want to maintain the requested URL like in SO, for e.g.:
www.stackoverflow/questions/tagged/php?foo=bar应该重定向到:
stackoverflow/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") ? "" : ""; 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") ? "" : ""; 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 推荐的方法,因为它保持 完整,以及端口等,如果您确实使用它们.
By the way, this is the method that is recommended by Google, as it keeps 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
发布评论