6

Im trying to write a little rest api in php by using mod_rewrite.

My question is: How do I handle HTTP DELETE and PUT? For example, the url would be: /book/1234

where 1234 is the unique id of a book. I want to "redirect" this id (1234) to book.php with the id as parameter. I already know how to read PUT and DELETE variables in the php script, but how do I set this rewrite rules in mod_rewrite?

Any ideas?

Edit: The rewriting rule for a GET would look like this:

RewriteRule book/([0-9]+) book.php?id=$1 [QSA] 

How do I do this "parameter forwarding" for PUT and DELETE? As far as I know HTTP POST, PUT and DELETE use the HTTP Request Body for transmitting parameter values. So I guess I need to append the parameter in the HTTP request body. But I have no idea how to do that with mod_rewrite.

Can I do some kind of mixing DELETE and GET?

RewriteCond %{REQUEST_METHOD} =DELETE
RewriteRule book/([0-9]+) book.php?id=$1 [QSA] 

Then in book.php I would user $_GET['id'] to retrieve the book id, even if the HTTP HEADER says that the HTTP METHOD is DELETE. It does not seems to work ...

sockeqwe
  • 15,574
  • 24
  • 88
  • 144

2 Answers2

5

There is a RewriteCond directive available. You can use it to specify that the following rule(s) just valid under a certain condition. Use it like this if you want to rewrite by HTTP request mthod:

RewriteCond %{REQUEST_METHOD} =PUT
RewriteRule ^something\/([0-9]+)$ put.php?id=$1

RewriteCond %{REQUEST_METHOD} =DELETE
RewriteRule ^something\/([0-9]+)$ delete.php?id=$1

# ...
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • yeah, but how do I pass the id (retrieved from the url) as a PUT parameter to the php script: /something/1234 Than i want that something.php can retrieve id = "123" somehow. For a HTTP GET i would do something like this: RewriteRule something/([0-9]+) something.php?id=$1 [QSA] . How do I do this parameter forwarding for PUT and DELETE? As far as I know I need to append a var in the HTTP Request body. But I have no idea how to do that with mod_rewrite – sockeqwe Feb 13 '13 at 10:00
  • Like in any other rewrite rule -> using regexes. You can follow a ton of tutorials. Or check my update – hek2mgl Feb 13 '13 at 11:59
3

Can I do some kind of mixing DELETE and GET?

Yes. You don't need to worry about the request method or the PUT body at all in your rewrite rules.

For your example this means:

mod_rewrite

RewriteRule book/([0-9]+) book.php?id=$1 [QSA]

HTTP request

PUT /book/1234
=> PUT /book.php?id=1234

PHP script

$id = intval($_GET['id']);
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    // yes, it is. go on as usual
}

For further clarification: The difference between GET parameters and PUT/POST/DELETE parameters is that the former are part of the URL, the latter part of the request body. mod_rewrite only changes the URL and does not touch the body.

Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111