>  기사  >  백엔드 개발  >  php_php 팁에서 사용자가 www 도메인 이름으로 리디렉션되도록 강제하는 방법

php_php 팁에서 사용자가 www 도메인 이름으로 리디렉션되도록 강제하는 방법

WBOY
WBOY원래의
2016-05-16 20:13:05975검색

이 기사의 예에서는 PHP가 사용자를 www 도메인 이름으로 리디렉션하도록 강제하는 방법을 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 구체적인 분석은 다음과 같습니다.

웹사이트의 www 도메인 이름과 www가 아닌 ​​도메인 이름으로 웹사이트에 액세스할 수 있는 경우가 있지만 이는 검색 엔진 포함에 도움이 되지 않으며 웹페이지의 무게를 분산시키므로 사용자가 영구적으로 해당 웹사이트로 리디렉션되기를 바랍니다. www가 아닌 ​​도메인 이름에 액세스할 때 www 도메인 이름은 301입니다. 예를 들어 사용자가 jb51.net을 방문하면 이 PHP 코드는 head를 통해 리디렉션될 수 없는 상황을 고려합니다. 사용자가 클릭할 수 있도록 페이지에 링크를 출력합니다.

// Install info.:
// Copy and paste these lines into your default index.php or
// the file that get's called if a visitor comes on your 
// website...
// read the host from the server environment
$host = $_SERVER["HTTP_HOST"];
// fix host name - we never now... ;-)
$host = strtolower($host);
$host = trim($host);
// This is important: 
// Webbrowsers like Firefox are doing their request without
// the port number like "www.jb51.net" but some other 
// applications send host names like "www.jb51.net:80" 
$host = str_replace(':80', '', $host);
$host = trim($host);
// if the host is not starting with www. redirect the 
// user to the same URL but with www :-)
if ($host != 'www.jb51.net'){
  // You an also change the "!=" to "==", if you want to force 
  // the user to use the domain name without the www. 
  // send status header, so that search engines or other services
  // detect that this is a permanent redirect and not a temporary
  header('HTTP/1.1 301 Moved Permanently');
  // read the URL the user requested:
  $url = isset($_SERVER["REQUEST_URI"]) ? $_SERVER["REQUEST_URI"] : '';
  // redirect the user to the new destination:
  header('Location: http://www.jb51.net' . $url);
  // Convert "special" chars -- cause we never now... ;-)
  $url = htmlspecialchars($url);
  // "fallback" link, if the browser is not supporting header redirects
  print '<a href="http://www.jb51.net' . $url.'">Please click here</a>';
  // stop the script execution here
  exit;
}
// If the domain is www.jb51.net then go on with your PHP code 
// of with your website...
// BTW: You need to replace jb51.net trough your own domain :-D

이 기사가 모든 사람의 PHP 프로그래밍 설계에 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.