Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a PHP query string into a slash-based URL?

I am a pretty skilled programmer, but when it comes to RegEx and rewriting, I am a total n00b. I want to convert a URL from

http://www.example.com/lookup.php?id=1

to

http://www.example.com/lookup/1/item/

where "item" refers to the name of an item in a database that is being looked-up.

I'm using LAMP (Linux, Apache, MySQL, PHP) and I cannot, for the life of me, figure out how to convert the URLs so they are SEO friendly.

like image 603
Seamus Campbell Avatar asked Nov 29 '10 06:11

Seamus Campbell


People also ask

Is query string part of URL?

A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters.

What is a query string in a URL?

A query string is a set of characters tacked onto the end of a URL. The query string begins after the question mark (?) and can include one or more parameters. Each parameter is represented by a unique key-value pair or a set of two linked data items. An equals sign (=) separates each key and value.

What is $_ server Query_string?

$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a query string. $_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request. $_SERVER['HTTP_ACCEPT_CHARSET']


2 Answers

Simple .htaccess example:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^lookup/([a-z0-9\-]+)/item/?$ /lookup.php?id=$1
</IfModule>

This will match any alphanumeric (also will recognise dashes) string of any length as the 'id'. You can limit this to just numeric by changing the regex to ([0-9]+).

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^lookup/([a-z0-9\-]+)/([a-z0-9\-]+)/?$ /lookup.php?id=$1&view=$2
</IfModule>

This one will match /lookup/123/some-text/ to /lookup.php?id=123&view=some-text

like image 91
levi Avatar answered Sep 20 '22 22:09

levi


Take a look on htaccess rewrite urls! :)

Here's your example:

RewriteRule ^lookup/(\d+)/(.*)$ /lookup.php?id=$1&name=$2

When you access lookup/123/my-product/, it'll call the lookup.php?id=123&name=my-product file internally.

like image 45
Thiago Belem Avatar answered Sep 20 '22 22:09

Thiago Belem