6

I have an API server that I am working on it currently accepts requests through $_GET variables like below

http://localhost/request.php?method=get&action=query_users&id=1138ab9bce298fe35553827792794394&time=1319225314&signature=d2325dedc41bd3bb7dc3f7c4fd6f081d95af1000

I need help creating a HTaccess rule that can read urls that replace the '&' with '/' and also the '=' and '?' with '/' to create a clean url like

http://localhost/request/method/get/action/query_users/id/1138ab9bce298fe35553827792794394/time/1319225314/signature/d2325dedc41bd3bb7dc3f7c4fd6f081d95af1000

Is there any way of doing this whilst still keeping the get parameters intact for the api to work from?

Also this is not the only request there are different requests that will be made.

Stackoverflow is always the place to go for expert advice so thanks in advance

Herbert
  • 5,698
  • 2
  • 26
  • 34
user866190
  • 855
  • 5
  • 14
  • 31
  • Seems like duplicate of http://stackoverflow.com/questions/1345314/apache-mod-rewrite-replace-character-with-another, see second answer – Dmytro Zavalkin Oct 21 '11 at 19:45
  • 1
    Judging from your example URI it seems you have a fundamental misunderstanding of RESTful APIs. A search for _representational state transfer_ will get you a lot more information on the subject. – Herbert Oct 21 '11 at 21:37

1 Answers1

22

This tends to be my standard answer to this kind of question, but why are you trying to do this with .htaccess rules when you could just do it in request.php, and that would be much more maintainable. Just parse the value of $_SERVER['REQUEST_URI'] in your php script.

//not really tested, treat as pseudocode
//doesn't remove the base url
$params = array();
$parts = explode('/', $_SERVER['REQUEST_URI']);
//skip through the segments by 2
for($i = 0; $i < count($parts); $i = $i + 2){
  //first segment is the param name, second is the value 
  $params[$parts[$i]] = $parts[$i+1];
}

//and make it work with your exsisting code
$_GET = $params;

With that in place, you should be able to request:

http://example.com/request.php/method/get/action/query_users/id/1138ab9bce298fe35553827792794394/time/1319225314/signature/d2325dedc41bd3bb7dc3f7c4fd6f081d95af1000

Or use this simple .htaccess:

RewriteRule ^request/ request.php

And request:

http://example.com/request/method/get/action/query_users/id/1138ab9bce298fe35553827792794394/time/1319225314/signature/d2325dedc41bd3bb7dc3f7c4fd6f081d95af1000
Tim Lytle
  • 17,549
  • 10
  • 60
  • 91
  • 1
    I've been searching forever for a good `.htaccess` solution and never thought of exploding the `REQUEST_URI` instead... You're right, much more maintainable, thanks! – Rémi Breton Jan 09 '13 at 21:54