This article mainly introduces the method of PHP forcing users to redirect to the www domain name, which can simulate the function of 301 redirection and output links when head redirection is not possible. The example in this article describes how PHP forces users to switch to the www domain name. Share it with everyone for your reference.
The specific analysis is as follows:
Sometimes the www domain name and non-www domain name of the website can access the website, but this is not conducive to the inclusion of search engines and will disperse the weight of the web page, so we hope that users will visit Non-www domain names are permanently redirected to www domain names through 301. For example, when users visit php.cn, they will be redirected directly to www.php.cn. This PHP code takes into account the situation that cannot be redirected through head, and will output the link on the page, so that User clicks.
// 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 '<a href="http://www.php.cn' . $url.'">Please click here</a>'; // 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
Related recommendations:
##In-depth analysis of php redirection (very useful)
php Several implementation methods of jumping page Example code
php Jump function, and Get the URL address of the current page
The above is the detailed content of php forces users to redirect to www domain name. For more information, please follow other related articles on the PHP Chinese website!