php removing www from url

隐身守侯 提交于 2020-01-06 21:24:06

问题


I am getting an error on a FB app when the url does not have the https or and has a www in the url. I am just going to strip the url of the www.

The code below adds the https if it is not in the url but how would I remove the www as well?

if(!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == ""){
    $redirect = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: $redirect");
}

回答1:


if(!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == ""){
    $redirect = str_replace('www.', '', "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: $redirect");
}

easiest way.




回答2:


Try to do it using .htaccess

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]



回答3:


Here is a way to do it with your .htaccess with https

RewriteEngine On
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
  • first line turns your RewriteEngine ... On
  • second line checks to see if https is ... on or
  • third line we check to see if the domain name starts with www
  • fourth line if either of the above conditions match rewrite the domain


来源:https://stackoverflow.com/questions/34005517/php-removing-www-from-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!