php强制用户转向www域名的方法
本文实例讲述了php强制用户转向www域名的方法。分享给大家供大家参考。具体分析如下:
有时候网站的www域名和非www域名都能访问网站,但是这样不利于搜索引擎的收录,会分散网页的权重,所以希望用户访问非www的域名时通过301永久重定向到www域名,例如用户访问jb51.net会直接转向www.nhooo.com,本php代码考虑了无法通过head重定向的情况,会在页面上输出链接,让用户点击。
//Installinfo.:
//Copyandpastetheselinesintoyourdefaultindex.phpor
//thefilethatget'scalledifavisitorcomesonyour
//website...
//readthehostfromtheserverenvironment
$host=$_SERVER["HTTP_HOST"];
//fixhostname-wenevernow...;-)
$host=strtolower($host);
$host=trim($host);
//Thisisimportant:
//WebbrowserslikeFirefoxaredoingtheirrequestwithout
//theportnumberlike"www.nhooo.com"butsomeother
//applicationssendhostnameslike"www.nhooo.com:80"
$host=str_replace(':80','',$host);
$host=trim($host);
//ifthehostisnotstartingwithwww.redirectthe
//usertothesameURLbutwithwww:-)
if($host!='www.nhooo.com'){
//Youanalsochangethe"!="to"==",ifyouwanttoforce
//theusertousethedomainnamewithoutthewww.
//sendstatusheader,sothatsearchenginesorotherservices
//detectthatthisisapermanentredirectandnotatemporary
header('HTTP/1.1301MovedPermanently');
//readtheURLtheuserrequested:
$url=isset($_SERVER["REQUEST_URI"])?$_SERVER["REQUEST_URI"]:'';
//redirecttheusertothenewdestination:
header('Location:https://www.nhooo.com'.$url);
//Convert"special"chars--causewenevernow...;-)
$url=htmlspecialchars($url);
//"fallback"link,ifthebrowserisnotsupportingheaderredirects
print'<ahref="https://www.nhooo.com'.$url.'">Pleaseclickhere</a>';
//stopthescriptexecutionhere
exit;
}
//Ifthedomainiswww.nhooo.comthengoonwithyourPHPcode
//ofwithyourwebsite...
//BTW:Youneedtoreplacejb51.nettroughyourowndomain:-D
希望本文所述对大家的php程序设计有所帮助。
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西