The example in this article describes the method of php to force users to redirect to www domain name. Share it with everyone for your reference. The specific analysis is as follows:
Sometimes the website's www domain name and non-www domain name can access the website, but this is not conducive to search engine inclusion and will disperse the weight of the web page. Therefore, we hope that users will permanently redirect to the www domain name through 301 when accessing non-www domain names. , for example, when users visit jb51.net, they will be redirected directly to www.jb51.net. This php code considers the situation that cannot be redirected through head, and will output a link on the page for users to click.
// 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.bkjia.com' . $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.bkjia.com' . $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
I hope this article will be helpful to everyone’s PHP programming design.