2015-02-09 132 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]