wojcik
wojcik

Reputation:

How can I make friendly urls for my site?

So far I include everything in index.php:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]

There are also pages where I use $_GET like this:

SELECT * FROM news WHERE id = ".intval($_GET['id'])

If I want to view a news I type news?id=1 instead of ?page=news&id=1 but I want to be able to use news/1.

Will I have to add a rewrite rule for every page where I use GET? Or is there a better way?

I hope I don't have to do this for all my pages.

Upvotes: 3

Views: 231

Answers (4)

Grant
Grant

Reputation: 12049

RewriteRule ^([^/]*)/?([^/]*)$ index.php?page=$1&id=$2 [QSA,L]

Should allow your pages to be entered as www.example.com/page/id

Most of your pages will internally look like www.example.com/index.php?page=text&id= but that shouldn't affect anything.

Upvotes: 5

Gumbo
Gumbo

Reputation: 655489

Try this rules:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)$ index.php?page=$1 [QSA,L]
RewriteRule ^([^/]+)/(\d+)$ index.php?page=$1&id=$2 [QSA,L]

Or you could parse the requested path with PHP:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^index\.php$ index.php [QSA,L]


// remove the query string from the request URI
$_SERVER['REQUEST_URI_PATH'] = preg_replace('/\?.*/', $_SERVER['REQUEST_URI']);
// removes leading and trailing slashes and explodes the path
$segments = explode('/', trim($_SERVER['REQUEST_URI_PATH'], '/'));
var_dump($segments);

Upvotes: 0

nezroy
nezroy

Reputation: 3186

Just use news/1, which will already work with your current rewrite rules and puts that value into the page parameter. Then create a generic URL dispatcher in your index.php that parses the value of the page parameter into component pieces, and decides what to do based on those pieces.

For example, a really simple generic dispatcher would just split the page parameter on "/", and then call a handler based on the value of the first item returned from the split (e.g. "news"), passing the rest of the pieces (e.g. "1") as arguments to the handler.

EDIT: Grammar, and a link to tutorials on URL dispatching in PHP.

Upvotes: 0

Cal
Cal

Reputation: 7157

this single rule should allow both with and without ids (and also makes the slashes optional):

RewriteRule ^([^/]*)(/([^/]*)/?)?$ index.php?page=$1&id=$3 [QSA,L]

if you don't want to allow / and //, change the *'s to +'s

Upvotes: 2

Related Questions