Saman
Saman

Reputation: 145

Should I use pk or a unique slug in my url?

I want to write the URLconf for a shopping cart app I wrote in django. I wonder what is the preferred way of constructing URLs.

The URL is accessible by the users via a hyperlink(They are not supposed to type it in the address bar). It adds the specified item to their shopping cart. should I

use the pk for the item:

http://example.com/add/253

or use a unique slug:

http://example.com/add/unique_item_slug

Do any of these approaches have security or performance advantage. Is there any reason to prefer one?

Upvotes: 2

Views: 2894

Answers (3)

Mirage
Mirage

Reputation: 31548

As Ewen said, the point of putting titles directly in the URL is SEO. Having keywords in the URL has a significant effect on search engine results

There isn't really any significant security risk with using the primary key in the URL, other than the ability for people to guess/predict other ones. But you shouldn't be relying on

nobody will guess this

as a security measure anyway.

Upvotes: 0

Aidan Ewen
Aidan Ewen

Reputation: 13308

The main reason for using slugs is SEO (Search, Engine Optimisation). The argument is that a search for 'My awesome widget' will return results which place -

http://example.com/products/my_awesome_widget

higher than

http://example.com/products/423

Google likes URL's that make sense to human beings. Ideally you want the URL to say as much about the page as possible. Have a look at the section 'Improve the Structure of your URLs' in googles SEO starter guide.

Since you're going to be selling things online, it's going to be important that web surfers easily find your products on search engines. Therefor the use of slugs is definitely recommended.

One disadvantage in depending solely on slugs is that you'll need to coerce the product name into an unique slug. You probably don't currently have a unique constraint on the product name, so you may have to do a bit of work creating the slug (by checking for whether the slug you're about to create already exists). A common solution is to include the slug and the product id.

http://example.com/products/my-awesome-widget/243

That way your slug doesn't have to be unique, but your url still includes the product name.

Upvotes: 6

Over the modern web development, you can do use your pk in the URL and that wouldn't be a problem.

Relying in a pretty restful design I would recomend you:

http://example.com/product/253/add

where the http://example.com/product/253 is your product detailed view.

Upvotes: 0

Related Questions