使用 PHP 将 WWW 重定向到非 WWW

编程入门 行业动态 更新时间:2024-10-26 14:37:49
本文介绍了使用 PHP 将 WWW 重定向到非 WWW的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想用 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

本文发布于:2023-07-16 03:51:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1117575.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重定向   PHP   WWW

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!