【问题标题】:HTaccess Rule To Tidy Up REST API requestsHTaccess 规则整理 REST API 请求
【发布时间】:2011-12-12 20:32:30
【问题描述】:

我有一个正在处理的 API 服务器,目前通过如下 $_GET 变量接受请求

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

我需要帮助创建一个 HTaccess 规则,该规则可以读取将 '&' 替换为 '/' 以及 '=' 和 '?' 的 URL使用 '/' 创建一个干净的 url,如

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

有什么方法可以做到这一点,同时仍然保持 api 的 get 参数不变?

此外,这不是唯一的请求,还会发出不同的请求。

Stackoverflow 始终是寻求专家建议的地方,因此在此先感谢

【问题讨论】:

  • 好像是stackoverflow.com/questions/1345314/…的副本,见第二个答案
  • 从您的示例 URI 来看,您似乎对 RESTful API 存在根本性的误解。搜索 representational state transfer 将为您提供有关该主题的更多信息。

标签: php api .htaccess rest


【解决方案1】:

这往往是我对这类问题的标准答案,但是你为什么要尝试使用 .htaccess 规则来做到这一点,而你可以在 request.php 中做到这一点,那会更易于维护。只需在您的 php 脚本中解析 $_SERVER['REQUEST_URI'] 的值即可。

//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;

有了这些,您应该可以请求:

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

或者使用这个简单的.htaccess

RewriteRule ^request/ request.php

请求:

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

【讨论】:

  • 我一直在寻找一个好的 .htaccess 解决方案,但从未想过要使用 REQUEST_URI 来代替...你说得对,更易于维护,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 2017-09-09
相关资源
最近更新 更多