Home > Software engineering >  Rewriting API url
Rewriting API url

Time:01-19

How can I configure NGINX to redirect my API URL?

I want to have /api/v1/projects/24 be redirected to /api/v1/projects/index.php?id=24

I thought this location block would work but I just get 404

location = /api/v1/projects {
                rewrite          ^/(/.*)$ /?id=$1 redirect;
}

CodePudding user response:

location = /api/v1/projects will not match /api/v1/projects/24, it only matches /api/v1/projects. See the location directive documentation.

If you want to externally redirect /api/v1/projects/24 to /api/v1/projects/index.php?id=24 (as your question suggests) you could just use a rewrite statement in the server block.

rewrite ^(/api/v1/projects)/(\d )$ $1/index.php?id=$2 redirect;

If you really mean to internally redirect the requested URL to a PHP handler, use:

rewrite ^(/api/v1/projects)/(\d )$ $1/index.php?id=$2 last;

See the rewrite directive documentation.

  • Related