Reverse Proxy

pyserve can act as a reverse proxy, forwarding requests to backend services.

Basic Proxy Configuration

Use the proxy_pass directive in routing:

extensions:
  - type: routing
    config:
      regex_locations:
        "~^/api/":
          proxy_pass: "http://localhost:9001"

All requests to /api/* will be forwarded to http://localhost:9001/api/*.

Proxy Headers

pyserve automatically adds standard proxy headers:

X-Forwarded-For Client's IP address
X-Forwarded-Proto Original protocol (http/https)
X-Forwarded-Host Original Host header
X-Real-IP Client's real IP address

Custom Headers

Add custom headers to proxied requests:

"~^/api/":
  proxy_pass: "http://localhost:9001"
  headers:
    - "X-Custom-Header: my-value"
    - "Authorization: Bearer token123"

Dynamic Headers with Captures

Use regex capture groups to build dynamic headers:

"~^/api/v(?P<version>\\d+)/(?P<service>\\w+)":
  proxy_pass: "http://localhost:9001"
  headers:
    - "X-API-Version: {version}"
    - "X-Service: {service}"
    - "X-Client-IP: $remote_addr"

Special variables:

Proxy Timeout

Configure timeout for proxy requests:

# Global default timeout
server:
  proxy_timeout: 30.0

# Per-route timeout
extensions:
  - type: routing
    config:
      regex_locations:
        "~^/api/slow":
          proxy_pass: "http://localhost:9001"
          timeout: 120  # 2 minutes for slow endpoints

URL Rewriting

The proxy preserves the original request path by default:

# Request: GET /api/users/123
# Proxied: GET http://backend:9001/api/users/123
"~^/api/":
  proxy_pass: "http://backend:9001"

To proxy to a specific path:

# Request: GET /api/users/123
# Proxied: GET http://backend:9001/v2/users/123 (path preserved)
"~^/api/":
  proxy_pass: "http://backend:9001/v2"

Load Balancing Example

Route different services to different backends:

extensions:
  - type: routing
    config:
      regex_locations:
        "~^/api/users":
          proxy_pass: "http://user-service:8001"
        
        "~^/api/orders":
          proxy_pass: "http://order-service:8002"
        
        "~^/api/products":
          proxy_pass: "http://product-service:8003"

Error Handling

pyserve returns appropriate error codes for proxy failures:

502 Bad Gateway Backend connection failed or returned invalid response
504 Gateway Timeout Backend did not respond within timeout
Note: pyserve uses httpx for async HTTP requests to backend services, supporting HTTP/1.1 and HTTP/2.