2015-02-09 135 views
-3

我试图根据定义的URL重定向用户。PHP 301重定向到定义的URL

如果定义的URL包含www和请求URL 包含www则用户被重定向到www版本的URL。

如果定义的URL不包含www和请求URL 确实包含www,则向用户重定向到非www版本的URL。

它还需要考虑子域和路径。

我曾尝试以下:

define(URL, 'localhost.com/cms'); 

$request = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]; 

if (get_subdomain(URL) != get_subdomain($request)) { 
    header("HTTP/1.1 301 Moved Permanently", true, 301); 
    header('Location:' . URL . $_SERVER['REQUEST_URI']); 
} 

function get_subdomain($url){ 
    $sub = parse_url($url); 
    return $sub['host']; 
} 
+0

您好海利。你能告诉我们你试过了什么吗? – 2015-02-09 10:27:34

+0

询问代码的问题应该至少包含一些代码或已经进行的尝试的描述。 – 2015-02-09 10:37:05

+0

@ RichardParnaby-King 我试过如下,它有一些问题。 define(URL,'http://localhost.com/cms'); $ request ='http://'.$_SERVER ['HTTP_HOST']。$ _ SERVER [“REQUEST_URI”];如果(get_subdomain(URL)!= get_subdomain($ request)){ \t header(“HTTP/1.1 301 Moved Permanently”,true,301); \t header('Location:'。URL。$ _SERVER ['REQUEST_URI']); } function get_subdomain($ url){ $ sub = parse_url($ url); return $ sub ['host']; } – haley 2015-02-09 10:38:10

回答

0

在示例代码中你已经在你正试图把它定义的函数。您需要将您的上述声明if你的函数调用:

function get_subdomain($url){ 
    $sub = parse_url($url); 
    return $sub['host']; 
} 

if (get_subdomain(URL) != get_subdomain($request)) { 
    header("HTTP/1.1 301 Moved Permanently", true, 301); 
    header('Location:' . URL . $_SERVER['REQUEST_URI']); 
} 

define功能要求其第一个参数的字符串。你也错过了你的网址中的http://

下面将比较路径(例如/cms)以查看用户是否请求了正确的页面(否则它们将不断重定向),然后比较主机。主机将包含www.或其他子域位。

为了便于阅读,我制作了if多行文字。

define('URL', 'http://localhost.com/cms'); 

$request = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]; 

$urlParts = parse_url(URL); 
$requestParts = parse_url($request); 

if($urlParts['path'] == $requestParts['path'] // Are we looking at the same pages 
    && 
    $urlParts['host'] !== $requestParts['host'] // Check domain. Will also include sub-domain 
) { 
    // Failed check. Redirect to URL 
    header("HTTP/1.1 301 Moved Permanently", true, 301); 
    header('Location:' . URL); 
} 

的替代的解决方案是执行上面在.htaccess文件:

# If url begins with www, and we are on the right page, redirect to the non-www version 
RewriteCond %{HTTP_HOST} ^www.localhost\.com 
RewriteRule ^cms% http://localhost.com/cms [R=301,L]