In Apache config file, there are some rules defines like below:

<IfModule mod_rewrite.c>
  RewriteRule   ^(Category)/([^/]+)/(.+)$     index.php?module=$1&id=$2&action=$3   [B,L,QSA]
  RewriteRule   ^(Listing)/(.+)$              index.php?module=$1&id=$2             [B,L,QSA]
  RewriteRule   ^([^/]+)/(.+)$                index.php?module=$1&action=$2         [B,L,QSA]

All this address http://web/foo/bar is internally translated (no redirects) into http://web/index.php?module=foo&id=bar: foo, bar are fed to index.php as params.

Now I want to add a rule which translates http://web/api?key1=val1&key2=val2 to http://web/api/index.php?key1=val1&key2=val2 in a similar manner.

I tried placing RewriteRule ^(api)//?(.+)$ api/index.php?$2 [B,L,QSA] at top of all rules, restarted apache but http://web/api?foo=bar becomes http://web/api/?foo=bar (with extra / after api) in browser's address bar and the call is redirected to http://web/index.php (as it throws error from the file).

How to change the RewriteRule to render http://web/api/index.php when request is made http://web/api?..?

1 Answer 1


The problem is that you have a api directory. The Apache code that handles redirects to add slashes to the directory is happening before the rewrite rule. Move your api directory to something else (like apiscripts) and then use the rewrite rule:

RewriteRule   ^api$ apiscripts/index.php [L,QSA]

You need the flags on the rewrite rule:

  • L (last) -- so that other rules don't also get triggered
  • QSA (query string append) -- so that mod_rewrite passes the parameters through

I would also recommend adding some conditions to your last rewrite rule to ensure that it isn't triggered for any paths that actually represent directories, files, or links:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^([^/]+)/(.+)$ index.php?module=$1&action=$2 [B,L,QSA]
  • I renamed api directory to apachescripts, but it is still giving 404 with that rule you mentioned.
    – Annie
    Commented Dec 10, 2014 at 11:01
  • I forgot to mention (don't know if it makes a difference), the web root is http://web/site/ and apiscripts are located http://web/site/apachescripts/index.php. The default index is located at http://web/site/index.php.
    – Annie
    Commented Dec 10, 2014 at 11:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.