我想檢查頁面的當前 URL 如果在查詢中包含 號 如果沒有 號我將重寫 URL 并 301 重定向到一個新的.. 例如
www.sitename.com/search?q=123 456
這應該是
www.sitename.com/search?q=123 456
首先,我想用 PHP 來做這個,首先是$_GET['q']干凈的字串,用 替換空格并與$_GET['q']URL 中的當前空格進行比較,但問題是因為我無法 登錄,$_GET而且很簡單,我無法檢查 URL包括 符號。
另一種選擇是使用.htaccess
RewriteCond %{QUERY_STRING} ^q=(.*)$
RewriteRule ^search$ test.php?mode=search&q=%1 [L]
但我相信這可以用 PHP 更好地完成,因為有更多的查詢引數不僅僅是q
有些想法是
$q1 = cleanq($_GET['q']) //This query include ,cleanq is function to clean string and replace space with
$q2 = $_GET['q'] //This is current one
if(strcmp($q1, $q2) != 0){
header("HTTP/1.1 301 Moved Permanently");
header("Location: www.sitename.com/search?q=".$q1);
exit();
}
看起來很簡單,但無法比較登錄查詢,知道如何制作嗎?
uj5u.com熱心網友回復:
由于 URL 規范,URL 中的字符 必須解釋為空格,因為 URL 中不允許使用純空格。
您不必擔心重定向www.sitename.com/search?q=123 456到www.sitename.com/search?q=123 456,它是同一個鏈接。
你可以在 PHP 檔案中做一個簡單的測驗:
test.php?search1=aaa bbb&search2=aaa bbb
if ($_GET['search1'] == $_GET['search2']) {
print 'Same string!';
}
你會得到Same string!
如果要更新當前 URL,可以使用 javascript 來完成,方法是將編碼的 url 空間替換 為
<script>
const url = window.location.href.replace(/%20/, " ");
window.history.replaceState(null, null, url)
</script>
PHP重定向使用$_SERVER['REQUEST_URI']
if (stripos($_SERVER['REQUEST_URI'], ' ') !== false) {
$request_uri = str_replace(' ', ' ', $_SERVER['REQUEST_URI']);
$request_uri = preg_replace('/([ ])\1 /', '$1', $request_uri);
if ($request_uri != $_SERVER['REQUEST_URI']) {
header("HTTP/1.1 301 Moved Permanently");
header("Location: " . $request_uri);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/532801.html
標籤:php.htaccess
下一篇:為什么我得到UncaughtTypeError:Cannotsetpropertiesofundefined(setting'src')?
