>  기사  >  백엔드 개발  >  PHP는 사용자가 www 도메인 이름으로 리디렉션하도록 강제합니다.

PHP는 사용자가 www 도메인 이름으로 리디렉션하도록 강제합니다.

*文
*文원래의
2017-12-28 11:10:052067검색

이 기사에서는 주로 PHP가 사용자를 www 도메인 이름으로 리디렉션하도록 하는 방법을 소개합니다. 이는 헤드 리디렉션이 불가능할 때 301 리디렉션 및 출력 링크를 시뮬레이션할 수 있습니다. 이 기사의 예에서는 PHP가 사용자에게 www 도메인 이름으로 전환하도록 강제하는 방법을 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요.

구체적인 분석은 다음과 같습니다.

웹사이트의 www 도메인 이름과 www가 아닌 ​​도메인 이름으로 웹사이트에 접속할 수 있는 경우가 있으나 이는 검색 엔진 포함에 도움이 되지 않으며 웹페이지의 무게를 분산시키게 됩니다. 따라서 사용자가 www가 아닌 ​​도메인 이름에 액세스할 때 항상 301을 전달하기를 바랍니다. 예를 들어 사용자가 php.cn을 방문하면 www.php.cn으로 직접 리디렉션됩니다. 코드는 헤드를 통해 리디렉션될 수 없는 상황을 고려하고 사용자가 클릭할 수 있도록 페이지에 링크를 출력합니다.


// 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.php.cn" but some other 
// applications send host names like "www.php.cn: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.php.cn'){
  // 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.php.cn' . $url);
  // Convert "special" chars -- cause we never now... ;-)
  $url = htmlspecialchars($url);
  // "fallback" link, if the browser is not supporting header redirects
  print &#39;<a href="http://www.php.cn&#39; . $url.&#39;">Please click here</a>&#39;;
  // stop the script execution here
  exit;
}
// If the domain is www.php.cn then go on with your PHP code 
// of with your website...
// BTW: You need to replace php.cn trough your own domain :-D

관련 권장 사항:

PHP 리디렉션에 대한 심층 분석(매우 유용함)

php 페이지 점프의 여러 구현 방법에 대한 예제 코드

php 점프 전송 기능 및 현재 페이지의 URL 주소 가져오기

위 내용은 PHP는 사용자가 www 도메인 이름으로 리디렉션하도록 강제합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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