Mod_rewrite: how to redirect HTTP DELETE and PUT

I am trying to write a little rest api in php using mod_rewrite.

My question is: How to handle HTTP DELETE and PUT? For example, the URL would be: / Book / 1234

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

Any ideas?

Edit: The rewrite rule for GET will look like this:

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

How do I do this "parameter transfer" for PUT and DELETE? As far as I know, HTTP POST, PUT and DELETE use the body of an HTTP request to pass parameter values. Therefore, I think I need to add this parameter to the body of the HTTP request. But I do not know how to do this with mod_rewrite.

Is there any way to mix DELETE and GET?

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

Then in book.php I would request the book identifier $ _GET ['id'], even if the HTTP HEADER says that the HTTP method is DELETE. It doesn't seem to work ...

+5
source share
2 answers

Is there any way to mix DELETE and GET?

Yes. You do not need to worry about the request method or the PUT body at all in your rewrite rules.

In 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 the GET parameters and the PUT / POST / DELETE parameters is that the first are part of the URL, the last part of the request body. mod_rewritechanges only the URL and does not touch the body.

+3
source

RewriteCond. , , . , HTTP- 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

# ...
+5

All Articles