Search code examples
phpregexapache.htaccessmod-rewrite

GET parameters not being correctly passed by RewriteRule


I wrote a simple regex for my application's API:

^api/([^/]+)/([^/.]+)\.([^$/?=&]+)(?:\?(.*))?$

this becomes

/app/api/$1.php?action=$2&format=$3&$4

In my testing, the regex works perfectly, constructing correct URLs, but the PHP script is not reporting any GET parameters apart from the action and format parameters. The .htaccess which is placed in / is

AddType image/svg+xml svg
RewriteEngine on
#If the URL is just /api, give them the docs
RewriteRule ^api/?$ /app/api/apidoc.php [L]
#Example api/user/update.json?x=fff&y=gggg
#http://refiddle.com/2ss
RewriteRule ^api/([^/]+)/([^/.]+)\.([^$/?=&]+)(\?(.*))?$ /app/api/$1.php?action=$2&format=$3&$4 [L]
#Example api/user/update?x=000&y=ffe
RewriteRule ^api/([^/]+)/([^/.&=]+)(\?((.*)*))?$ /app/api/$1.php?action=$2&$3 [L]

Solution

  • Don't try to capture additional query string parameters. Instead, append them with the QSA flag.

    RewriteRule ^api/([^/]+)/([^/.]+)\.([^$/?=&]+) /app/api/$1.php?action=$2&format=$3 [L,QSA]
    

    Adjust your RewriteRule accordingly.