Rich
Rich

Reputation: 512

in url's, what's better to use to replace spaces, + or a dash? url encode does + , google recommend a dash

I'm working with mod_rewrite, and using page titles e.g. About Us that have been entered in the content management system instead of index.php?page=1

So I've got a rule

RewriteRule     ^pages/([A-Za-z0-9\-]+).php?$   index.php?page=$1                   [NC,L]  # Handle site navigation

which will look nice as a url www.domain.com/pages/About-Us.php and send requests to www.domain.com/index.php?page=About-Us

However url encode puts a plus sign in for spaces, so if I query About-Us it doesn't work obviously, because what I should query is domain.com/About+Us.php

I want to use the About-Us.php version, how do I get url encode to handle my spaces with a - instead of + ?

Rich :)

Upvotes: 0

Views: 1462

Answers (1)

lanzz
lanzz

Reputation: 43198

urlencode() is intended for query parameters only (everything that goes after the ?). + is a special character inside the query part of the URL, and represents a literal space; literal + character needs to be percent-encoded. rawurlencode() is intended for all other URL parts, and it does not encode space as +.

Dashes on the other hand are not special characters and represent themselves in the URL directly.

You haven't specified which CMS you are using, or if it is your own in-house solution, but what you want to do is use slugs in the URL instead of the actual page title.

Most CMSes create a slug for each page automatically when it is created, by converting title to lowercase and replacing spaces and punctuation with dashes. Ideally, this slug should be an actual field in your database, so that it can be overridden manually when needed. When you generate links to your pages, you include their slug in the URL, and when you get a request for a page, you look it up in your database by slug, not by title.

Upvotes: 4

Related Questions