0

I've the following code in .htaccess file for the folder /rest-api inside main root folder.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\?*$ /rest-api/index.php?__route__=/$1 [L,QSA]

So, I need to migrate it into nginx server block, I'm trying serveral options but nothing works. The best approach I've found is:

location /rest-api {
   if (!-e $request_filename){
      rewrite ^/(.*)\?*$ /index.php?__route__=/$1;
   }
}

But it downloads a file when it should convert the url. Anybody can help me? Thanks!!

1 Answer 1

0

I think your regex is broken, its author means ^(.*)\?.*$ and wants to keep an URI part without the query string. NGINX works with the normalized URI without the query string part, so you can try this one:

location /rest-api {
    try_files $uri $uri/ /rest-api/index.php?__route__=$uri&$args;
}

The only caveat of above config is that it would pass an extra & if an HTTP request doesn't have any query arguments at all. Generally it shouldn't lead to any trouble, but if it is, some more accurate version of config is

location /rest-api {
    set $qsa '';
    if ($args) {
        set $qsa '&';
    }
    try_files $uri $uri/ /rest-api/index.php?__route__=$uri$qsa$args;
}

Update

I'm not very familiar with Apach mod_rewrite, but if you need to use an URI part without the /rest-api prefix as __route__ query argument, try this:

location = /rest-api {
    # /rest-api to /rest-api/ redirect is for safety of the next location block
    rewrite ^ /rest-api/ permanent;
}
location /rest-api/ {
    set $qsa '';
    if ($args) { set $qsa $args; }
    rewrite ^/rest-api(.*)$ $1 break;
    try_files /rest-api$uri /rest-api$uri/ /rest-api/index.php?__route__=$uri$qsa$args;
}
2
  • Hey Ivan, tried and not working the two configurations provided. As far as I know, the main idea with that URL is for example: https:something.com/rest-api/hello-world convert it into https:/something.com/rest-api/index.php?hello-world. Thanks for your support!
    – David M.
    Commented Apr 20, 2021 at 17:15
  • @DavidM. Can you check an updated version? Commented Apr 25, 2021 at 11:34

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.