开发者

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/'开发者_Python百科 );
    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


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.


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"], "_", " ");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜