PHP 上 REST API 的 mod_rewrite
我希望每次调用
http://localhost/api/
(作为根文件夹),例如 http://localhost/api/get/users
实际上是 http://localhost/api /index.php?handler=get/users
。
http://localhost/api/get/user/87
应该是 http://localhost/api/index.php?handler=get/user/87
其中index.php 我会捕获 $_GET 变量 handler 并以正确的方式处理它。
如果我有这种重写规则,它仅适用于一
RewriteRule ^([^/\.]+)/?$ index.php?handler=$1 [QSA,L]
二三
RewriteRule ^([^/\.]+)/?$ index.php?handler=$1 [QSA,L]
RewriteRule ^([^/\.]+)/([^/\.]+)/?$ index.php?handler=$1&handler2=$2 [QSA,L]
斜杠等等...
RewriteRule ^([^/\.]+)/?$ index.php?handler=$1 [QSA,L]
RewriteRule ^([^/\.]+)/([^/\.]+)/?$ index.php?handler=$1&handler2=$2 [QSA,L]
RewriteRule ^([^/\.]+)/([^/\.]+)/([^/\.]+)/?$ index.php?handler=$1&handler2=$2&handler3=$3 [QSA,L]
因此,对于第一种情况 http://localhost/api/a
可以工作,但是 http://localhost/api/a/b
会导致 Not Found 错误。
编辑:这样应该可以吗?
RewriteRule ^(.*)$ index.php?handler=$1 [L,QSA]
I want that every call with
http://localhost/api/
(as root folder) for example http://localhost/api/get/users
actually is http://localhost/api/index.php?handler=get/users
.
http://localhost/api/get/user/87
should be http://localhost/api/index.php?handler=get/user/87
where in index.php I would catch $_GET variable handler and handle it in proper way.
If I have this kind of rewrite rules it works only for one
RewriteRule ^([^/\.]+)/?$ index.php?handler=$1 [QSA,L]
two
RewriteRule ^([^/\.]+)/?$ index.php?handler=$1 [QSA,L]
RewriteRule ^([^/\.]+)/([^/\.]+)/?$ index.php?handler=$1&handler2=$2 [QSA,L]
three slashes and so on...
RewriteRule ^([^/\.]+)/?$ index.php?handler=$1 [QSA,L]
RewriteRule ^([^/\.]+)/([^/\.]+)/?$ index.php?handler=$1&handler2=$2 [QSA,L]
RewriteRule ^([^/\.]+)/([^/\.]+)/([^/\.]+)/?$ index.php?handler=$1&handler2=$2&handler3=$3 [QSA,L]
So for the first case http://localhost/api/a
would work, but http://localhost/api/a/b
would cause a Not Found error.
EDIT: Should this be fine?
RewriteRule ^(.*)$ index.php?handler=$1 [L,QSA]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您(自己的)答案应该没问题,只需记住它会将所有传入 URL 重定向到
index.php
。即,如果您有静态文件,例如/js/jquery.js
那么它将更改为index.php?handler=/js/jquery.js
。如果您想避免问题,请尝试以下操作:
两个提示:
请尝试使用
RewriteLog
指令:它可以帮助您追踪此类问题:我最喜欢的检查正则表达式的工具:
http://www.quanetic.com/Regex(不要忘记选择 ereg(POSIX) 而不是 preg(PCRE)!)
Your (own) answer should be fine, just keep in mind that it will redirect all incoming URLs to
index.php
. I.e. if you have static files, for example/js/jquery.js
then it will be changed toindex.php?handler=/js/jquery.js
.If you want to avoid problems try something like:
Two hints:
Please try to use the
RewriteLog
directive: it helps you to track down such problems:My favorite tool to check for regexp:
http://www.quanetic.com/Regex (don't forget to choose ereg(POSIX) instead of preg(PCRE)!)