Forward API Requests to a Backend Service

Understand the reverse proxy request flow and how proxy_pass preserves or replaces paths.

🎯 Introduction

So far, Nginx has served HTML and CSS files. In this article, you will use Nginx to create a mock backend on port 9001 that returns fixed JSON for /notes, then use curl to verify that the site entry point on port 8080 forwards API requests to it.


🧱 Distinguish the Three Roles

The client (curl here) requests /api/notes from the site entry point. The entry point forwards the request to the mock backend according to its /api/ rule, then sends the backend's response back to the client. The client needs to know only the entry point's address. This is reverse proxying.

The backend receiving forwarded requests is also called an upstream service. It can later be replaced with a Node.js application or a program in another language. The proxy and backend do not need to use the same technology.

The main exercise still runs on one machine: the entry point listens on 127.0.0.1:8080, and the mock backend on 127.0.0.1:9001. Different ports simulate two roles within the same Nginx instance; they do not provide the process isolation of separate applications.


🛠 Prepare a Directly Accessible Mock Backend

Create conf/servers/mock.conf:

conf/servers/mock.conf
server {
    listen 127.0.0.1:9001;
    server_name backend-a;
    default_type application/json;

    location = /notes {
        add_header X-Backend 'a';
        add_header X-Seen-URI $request_uri;
        return 200 '{"instance":"a","notes":["learn nginx"]}';
    }

    location / {
        return 404 '{"error":"not found"}';
    }
}

JSON is a common data interchange format. Here, "notes" is an example field name, and "learn nginx" inside the brackets is test data written directly in the return directive. Nginx sends this fixed JSON to the client when /notes is requested.

$request_uri contains the original request path and query string. The exercise's X-Seen-URI response header shows what the backend actually received. Check and reload, then connect directly to the backend first:

curl -i http://127.0.0.1:9001/notes

Expect 200, X-Backend: a, and the JSON defined above. Confirm that the mock backend is directly accessible before configuring forwarding.


🛠 Add a Proxy to the Site Entry Point

Add these two blocks inside the server in site.conf. Keep the existing asset and page rules:

location = /api {
    return 308 /api/;
}

location ^~ /api/ {
    proxy_pass http://127.0.0.1:9001/;
}

308 is a redirect that tells the client to request another URL while preserving the original request method. Adding the trailing slash in /api/ makes the subsequent prefix rule work consistently.

Check and reload, then run:

curl -i 'http://127.0.0.1:8080/api/notes?type=public'

Expect 200 and JSON, with X-Seen-URI showing /notes?type=public. Single quotes keep the whole URL as one argument and prevent the shell from interpreting special characters as operators.


🪤 A Trailing Slash in proxy_pass Changes the Path

For the plain prefix location used here, without additional rewrites or variables, the rules are:

ConfigurationBrowser requestUpstream receives
proxy_pass http://127.0.0.1:9001/;/api/notes/notes
proxy_pass http://127.0.0.1:9001;/api/notes/api/notes
proxy_pass http://127.0.0.1:9001/v1/;/api/notes/v1/notes

The key is whether the address includes a URI component, rather than just whether it ends in a slash. If a URI is present, it replaces the matched /api/ prefix. Without one, this example preserves the request path. Complex rewrites, variables, and regular expression locations have additional constraints; this table does not apply to all of them. See the official proxy_pass documentation.


❓ Questions and Answers

Q1: Why does the backend return 404 through the proxy?

Check the path the backend actually received. If it recognizes only /notes but receives /api/notes, fix the path mapping. Do not hide the error behind a home page fallback.

Q2: Does Nginx handle login and permissions for the backend?

Not in this example. It forwards requests; the application still validates user identity and business permissions.


🧪 Exercise

Temporarily remove the trailing / from the proxy_pass address, check and reload, then request /api/notes. Restore the configuration afterward.

Check your result: removing the slash produces a backend JSON 404; restoring it produces JSON with status 200. Then request /api/missing: it should still return the backend's JSON 404, never the home page HTML.


🎉 You can now work backward from the path received by the backend to understand the proxy configuration!