Mod_rewrite for REST API in PHP

I want every call with

http://localhost/api/ 

(like the root folder ), e.g. http://localhost/api/get/users is actually 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 the variable $ _GET handler and process it properly.

If I have such rewriting rules, it only works 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, etc.

 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 will work, but http://localhost/api/a/b will result in a Not Found error.

EDIT . Should it be good?

 RewriteRule ^(.*)$ index.php?handler=$1 [L,QSA] 
+6
source share
1 answer

Your (own) answer should be fine, just keep in mind that it will redirect all incoming URLs to index.php . That is, 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 tips:

Try using the RewriteLog directive: this will help you identify such problems:

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

My favorite regexp checker tool:

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

+9
source

Source: https://habr.com/ru/post/904503/


All Articles