PHP上的REST API的mod_rewrite

sve*_*ija 6 php api rest mod-rewrite

我想要每次通话

http://localhost/api/
Run Code Online (Sandbox Code Playgroud)

(作为根文件夹)例如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/87index.php中的哪个地方我会捕获$ _GET变量处理程序并以正确的方式处理它.

如果我有这种重写规则,它只适用于一个

RewriteRule ^([^/\.]+)/?$ index.php?handler=$1 [QSA,L]
Run Code Online (Sandbox Code Playgroud)

RewriteRule ^([^/\.]+)/?$ index.php?handler=$1 [QSA,L]
RewriteRule ^([^/\.]+)/([^/\.]+)/?$ index.php?handler=$1&handler2=$2 [QSA,L]
Run Code Online (Sandbox Code Playgroud)

三个斜线等...

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]
Run Code Online (Sandbox Code Playgroud)

因此,对于第一种情况http://localhost/api/a可行,但http://localhost/api/a/b会导致Not Found错误.

编辑:这应该没事吗?

RewriteRule ^(.*)$ index.php?handler=$1 [L,QSA]
Run Code Online (Sandbox Code Playgroud)

Oli*_*ons 9

您的(自己的)答案应该没问题,请记住它会将所有传入的URL 重定向到index.php.即如果您有静态文件,例如/js/jquery.js它将被更改为index.php?handler=/js/jquery.js.

如果你想避免问题,请尝试以下方法:

RewriteCond %{REQUEST_URI} !(.*)\.(css|js|htc|pdf|jpg|jpeg|gif|png|ico)$ [NC]
RewriteRule ^(.*)$ index.php?handler=$1 [QSA,L]
Run Code Online (Sandbox Code Playgroud)

两个提示:

请尝试使用该RewriteLog指令:它可以帮助您跟踪此类问题:

# Trace:
# (!) file gets big quickly, remove in prod environments:
RewriteLog "/web/logs/mywebsite.rewrite.log"
RewriteLogLevel 9
RewriteEngine On
Run Code Online (Sandbox Code Playgroud)

我最喜欢检查regexp的工具:

http://www.quanetic.com/Regex(别忘了选择ereg(POSIX)而不是preg(PCRE)!)