apache.htaccessmod-rewriteurl-rewritingclean-urls

Mod Rewrite - Clean URL with query string not working


I have the following .htaccess file.

<IfModule mod_rewrite.c> 
    Options +FollowSymlinks
    RewriteEngine On
    DirectoryIndex api.php
    FallbackResource index.php

    RewriteCond %{REQUEST_URI} ^/api
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{QUERY_STRING} ^$
    RewriteRule ^/([^/]+)/([^/]+)$ $1/$1.php?endpoint=$2 [L]
    RewriteRule ^([^/]+)/([^/]+)/([^/]+)$ $1/$1.php?endpoint=$2&id=$3 [L]
    RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)$ $1/$1.php?endpoint=$2&id=$3&endpoint2=$4 [L]
    RewriteCond %{QUERY_STRING} ^(.*)$
    RewriteRule ^([^/]+)$ $1/$1.php  [L]
    RewriteRule ^([^/]+)/([^/]+)? $1/$1.php?endpoint=$2%1 [QSA,L]
    RewriteRule ^/([^/]+)/([^/]+)/([^/]+)? $1/$1.php?endpoint=$2&id=$3%1 [QSA,L]
    RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)? $1/$1.php?endpoint=$2&id=$3&endpoint2=$4%1 [QSA,L]
</IfModule> 

I want to rewrite api endpoints (clean url format with possible query at end of last token) into a query string format entirely as shown below.

Example

api/users/123/actionitems

currently reads

api/api.php?endpoint=users&id=123&endpoint2=actionitems

{
    endpoint: users,
    id: 123,
    endpoint2: actionitems
}  

But I also want to convert

api/users/123/actionitems?test=3

into

api/api.php?endpoint=users&id=123&endpoint2=actionitems&test=3

{
    endpoint: users,
    id: 123,
    endpoint2: actionitems,
    test: 3
}  

It doesn't work. I get only

api/api.php?endpoint=users&id=123&endpoint2=actionitems

when I type

/api/users/123/actionitems?test=3

{
    endpoint: users,
    id: 123,
    endpoint2: actionitems
}  

And only when I type /api/users/123/actionitems&test=3 instead of question mark (/api/users/123/actionitems?test=3) in my request it works.

How do I get this to work?


Solution

  • You can use the following single rule :

        Options +FollowSymlinks
        RewriteEngine On
        DirectoryIndex api.php
        FallbackResource index.php
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^api/([^/]+)/([^/]+)/([^/]+)/?$  /api/api.php?endpoint=$1&id=$2&endpoint2=$3 [QSA,L]