Callum Whyte
Callum Whyte

Reputation: 2429

Formatting URLs with .htaccess and PHP

I have a search engine script that formats it's URLs from a .htaccess file. However, when a search is made on the site, the search URL has /search/QUERY%20TERMS/1/. (Notice the %20 in between each word). Is there any way with PHP or .htaccess that I can have + instead of %20?

My .htaccess code is currently this. It formats the SERP URLs.

RewriteEngine on
RewriteRule ^search/([^/]+)/([^/]+)/?$ search.php?q=$1&category=web&d=$2
RewriteRule ^search/([^/]+)/$ /search/$1/1/ [R=301,L]
RewriteRule ^search/([^/]+)$ /search/$1/1/ [R=301,L]
RewriteRule ^search/?$ / [R=301,L]

And my PHP code is currently this. It allows the search box to go to the correct SERP as it has a complicated URL structure.

<?PHP
if( isset( $_POST['q'] ) )
{
    header( 'location: search/' . $_POST['q'] . '/1/' );
    exit();
}
?>

How can I get my URLs to have + instead of %20 in PHP or .htaccess?

Any help is much appreciated, thanks in advance. Callum

Upvotes: 0

Views: 338

Answers (2)

mario
mario

Reputation: 145482

An alternative to urlencode() would be to transliterate the space for another character. For example wikipedia uses the _ underscore in place of spaces, which would look nicer than the + from urlencode.

header( 'location: search/' . (strtr($_POST['q'], " ", "_")) . '/1/' );
// actually you should still apply urlencode() for other special chars

Of course this necessitates undoing the same in the search script:

$q = strtr($_GET["q"], "_", " ");

Upvotes: 1

Treffynnon
Treffynnon

Reputation: 21553

You can just urlencode() (man page) it before performing your redirect like so:

<?PHP
if( isset( $_POST['q'] ) )
{
    header( 'location: search/' . urlencode($_POST['q']) . '/1/' );
    exit();
}
?>

This doesn't have anything to do with .htaccess or mod_rewrite. It is about the URL being passed to the server in the correct format in the first place.

Upvotes: 1

Related Questions