Reverse Proxy in API Gateway — How It Works and Why It Matters
In this tutorial, you will learn about Reverse Proxy in API Gateway. We cover key concepts, practical examples, and best practices to help you master this topic.
A reverse proxy is the core mechanism that allows an API gateway to receive client requests, forward them to backend services, and return responses without exposing internal infrastructure to the outside world.
What You'll Learn
- How a reverse proxy differs from a forward proxy
- How gateways use reverse proxying to hide backend services
- Header forwarding, path rewriting, and common proxy configurations
Why It Matters
Exposing backend services directly to the internet creates a massive security risk. Attackers can probe internal APIs, discover service names, and exploit vulnerabilities. A reverse proxy hides all internal details, presenting a single , hardened surface to the outside world.
Real-World Use
When a partner integration sends a threat report to Durga Antivirus, the request hits the gateway at api.dodatech.com/report. The gateway strips the external domain, rewrites the path to /internal/v2/report, adds internal authentication headers, and forwards to the threat analysis service running on a private subnet.
flowchart LR
Internet["Internet"] --> GW["Reverse Proxy / Gateway"]
GW --> Backend1["Backend A\n192.168.1.10"]
GW --> Backend2["Backend B\n192.168.1.11"]
style GW fill:#dbeafe,stroke:#2563eb
style Backend1 fill:#e5e7eb,stroke:#6b7280
style Backend2 fill:#e5e7eb,stroke:#6b7280
How a Reverse Proxy Works
A reverse proxy sits between clients and servers. When a request arrives:
- The proxy receives the request on a public IP and port
- It inspects the request (path, headers, method)
- It determines which backend should handle it
- It optionally rewrites the path or modifies headers
- It forwards the request to the backend
- It receives the backend response and relays it to the client
Forward Proxy vs. Reverse Proxy
| Aspect | Forward Proxy | Reverse Proxy |
|---|---|---|
| Position | Client side | Server side |
| Purpose | Hide client IP | Hide server IP |
| Typical use | Bypass geo-restrictions | Load balance, security |
| Client awareness | Client configures it | Client unaware |
Path Rewriting
A common reverse proxy task is rewriting request paths. The external path /api/v2/users/42 might map to internal path /users/42 on the user service.
import re
from flask import Flask, request
import requests
app = Flask(__name__)
ROUTES = {
r"^/api/v2/users/(.*)$": ("http://user-service:8080/users/{}", 1),
r"^/api/v2/orders/(.*)$": ("http://order-service:8080/orders/{}", 1),
}
@app.route("/api/v2/<path:rest>")
def proxy(rest):
full_path = f"/api/v2/{rest}"
for pattern, (template, group_count) in ROUTES.items():
match = re.match(pattern, full_path)
if match:
backend_url = template.format(*match.groups())
resp = requests.request(
method=request.method,
url=backend_url,
headers={k: v for k, v in request.headers if k.lower() not in ("host",)},
data=request.get_data()
)
return (resp.content, resp.status_code, resp.headers.items())
return {"error": "No route matched"}, 404
Header Manipulation
The proxy often adds or removes headers before forwarding:
def prepare_headers(original_headers):
headers = {k: v for k, v in original_headers if k.lower() not in ("host", "x-internal-token")}
headers["X-Forwarded-For"] = request.remote_addr
headers["X-Forwarded-Proto"] = request.scheme
headers["X-Internal-Auth"] = "secret-gateway-token"
return headers
The backend receives X-Forwarded-For with the real client IP, while the client never sees internal IPs or the internal auth token.
Common Mistakes
1. Forwarding the Host Header Incorrectly
Backends may reject requests if the Host header doesn't match. Strip or rewrite the Host header before forwarding.
2. Leaking Internal IPs
If the proxy includes X-Internal-* headers meant for backends, clients may see them. Explicitly strip internal headers from responses.
3. Buffering Large Requests Without Limits
Without request size limits, a malicious client can send a multi-gigabyte payload and exhaust proxy memory.
4. Breaking WebSocket Connections
Standard HTTP proxies may not support the WebSocket upgrade handshake. Ensure the proxy is configured for WebSocket passthrough.
5. Not Handling Chunked Transfer Encoding
Some proxies struggle with Transfer-Encoding: chunked. Use a proxy library that handles streaming properly.
Practice Questions
- What is the primary difference between a forward proxy and a reverse proxy?
- Why should backend services never be directly exposed to the internet?
- How does path rewriting help decouple external URLs from internal service structure?
- What does the
X-Forwarded-Forheader contain and why is it important? - Why must internal-only headers be stripped from responses before returning to clients?
Answers:
- A forward proxy hides the client IP; a reverse proxy hides the server IP and infrastructure.
- Direct exposure reveals internal IPs, service names, and potential attack surfaces that a hardened gateway can protect.
- Path rewriting lets the organization change internal routing without breaking external clients, since the public path stays unchanged.
- It contains the original client IP address, which the backend needs for logging, geo-location, and rate limiting.
- Internal headers could expose backend IPs, authentication tokens, or infrastructure details that aid attackers.
Challenge: Configure Nginx as a reverse proxy for two Node.js applications running on ports 3001 and 3002. Route /app1/* to port 3001 and /app2/* to port 3002.
FAQ
Mini Project
Build a Node.js Express reverse proxy that forwards requests to two backend services: a Python Flask app and a Go HTTP server. Implement path-based routing, header manipulation (add X-Proxy: true), and a catch-all error handler.
What's Next
Continue with Gateway Routing Strategies to learn path-based, header-based, and weight-based routing, or explore Load Balancing in Gateways for distributing traffic across instances.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro