用于PHP上REST API的mod_rewrite [英] mod_rewrite for REST API on PHP

查看:52
本文介绍了用于PHP上REST API的mod_rewrite的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望每次致电

http://localhost/api/

(作为根文件夹),例如http://localhost/api/get/users实际上是http://localhost/api/index.php?handler=get/users.

(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应该是http://localhost/api/index.php?handler=get/user/87,在 index.php 中,我会捕获$ _GET变量 handler 并以正确的方式对其进行处理.

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]

两个

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]

因此对于第一种情况,http://localhost/api/a可以工作,但是http://localhost/api/a/b会导致未找到错误.

So for the first case http://localhost/api/a would work, but http://localhost/api/a/b would cause a Not Found error.

编辑:可以吗?

RewriteRule ^(.*)$ index.php?handler=$1 [L,QSA]

推荐答案

您的(自己的)答案应该不错,只需记住它将把所有传入的URL重定向到index.php. IE.如果您有静态文件,例如/js/jquery.js,则它将更改为index.php?handler=/js/jquery.js.

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 to index.php?handler=/js/jquery.js.

如果要避免出现问题,请尝试以下操作:

If you want to avoid problems try something like:

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

两个提示:

请尝试使用RewriteLog指令:它可以帮助您查找此类问题:

Two hints:

Please try to use the RewriteLog directive: it helps you to track down such problems:

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


我最喜欢的用于检查正则表达式的工具:


My favorite tool to check for regexp:

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

http://www.quanetic.com/Regex (don't forget to choose ereg(POSIX) instead of preg(PCRE)!)

这篇关于用于PHP上REST API的mod_rewrite的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆