mod_rewrite for REST API on PHP

2019-03-13 23:23发布

问题:

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]

回答1:

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]

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 (don't forget to choose ereg(POSIX) instead of preg(PCRE)!)