I want to check the current URL of the page if include sign in the query if there is no sign I will rewrite the URL and 301 redirect to a new one.. for example
www.sitename.com/search?q=123 456
this should be
www.sitename.com/search?q=123 456
First I was thinking to make this with PHP, first, $_GET['q']
and clean string, replace space with and compare with the current one $_GET['q']
in URL but the problem is because I can't get sign in $_GET
and simple I can't check if URL include sign
.
Another option is to make this with .htaccess
RewriteCond %{QUERY_STRING} ^q=(.*)$
RewriteRule ^search$ test.php?mode=search&q=%1 [L]
But I believe this can be better done with PHP because there is more query parameter that isn't just q
Some ideas were
$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();
}
Looks simple but can't get the sign-in query to compare, any idea how to make this?
CodePudding user response:
Because of the URL specification, the character
in URLs must be interpreted as a space, as plain spaces are not allowed in URLs.
You don't have to worry about redirecting www.sitename.com/search?q=123 456
to www.sitename.com/search?q=123 456
, it's the same link.
You can do a simple test in a PHP file:
test.php?search1=aaa bbb&search2=aaa bbb
if ($_GET['search1'] == $_GET['search2']) {
print 'Same string!';
}
You'll get Same string!
If you want to update the current URL you can do it with javascript, by replacing the encoded url space
with
<script>
const url = window.location.href.replace(/ /, " ");
window.history.replaceState(null, null, url)
</script>
PHP redirect using $_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);
}
}