Skip to main content

Rewriting URL path in nginx without redirecting [Resolved]

For legacy reasons, I have URLs like I want /foo.cgi?id=nnn to respond with the contents of a file nnn.html, where nnn is a number that varies.

In nginx, how do I define a custom mapping from URL paths to different file paths without generating redirects? (That is, while I want the contents of nnn.html to be served, I want the browser-visible URL to continue to be foo.cgi?id=nnn.)

Question Credit: hsivonen
Question Reference
Asked June 14, 2019
Tags: nginx
Posted Under: Network
1 Answers

Assuming that the URI /foo.cgi is defunct, you can use an exact match location block to process the id argument using a try_files statement.

For example:

location = /foo.cgi {
    root /path/to/files;
    try_files /$arg_id.html =404;

The URI /foo.cgi?id=123 will cause Nginx to search for a file at /path/to/files/123.html or return a 404 status if not found.

credit: Richard Smith
Answered June 14, 2019
Your Answer