views:

151

answers:

4

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.

+5  A: 
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.

Grant
Ok, I change a few things around, it shouldn't require a slash at the end anymore.
Grant
A: 

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.

nezroy
+1  A: 

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

Cal
+ matches 1 or more, ? matches 0 or 1. Shouldn't it be a '?'?
goldenratio
yes! very good man. thank you
A: 

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);
Gumbo