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

查看:21
本文介绍了用于 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]

三个斜线等等...

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 会导致 http://localhost/api/a/bstrong>未找到错误.

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.html.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天全站免登陆