Skip to main content
When running FastAPI behind a reverse proxy (like Nginx, Apache, or a cloud load balancer), you need to configure your application to correctly handle proxied requests and generate accurate URLs.

Understanding Proxy Scenarios

Reverse proxies sit between clients and your FastAPI application:
The proxy may:
  • Terminate SSL/TLS (serve HTTPS while talking to your app over HTTP)
  • Add a path prefix (serve your app at /api/v1 instead of /)
  • Forward headers about the original request
Without proper configuration, your FastAPI app won’t know about the original request’s protocol, host, or path.

Root Path

When your app is mounted at a path prefix, use the root_path parameter:

Reading Root Path from Request

Setting Root Path in Application

Now the app expects to be accessed at /api/v1/app instead of just /app.
The root_path affects the OpenAPI schema URL. Your docs will be at /api/v1/docs instead of /docs.

Configuring with Servers

Define alternative server URLs in the OpenAPI schema:
This configuration:
  • Shows multiple server options in the docs
  • Sets the path prefix to /api/v1
  • Allows users to test against different environments

Controlling Root Path in Servers

By default, root_path is included in server URLs. To disable this:

Nginx Configuration

Basic Proxy Setup

Proxy with Path Prefix

Configure your FastAPI app:

SSL Termination

Traefik Configuration

Configure your FastAPI app:

Environment-Based Configuration

Set root_path from environment variables:
Run with environment variables:

Docker and Kubernetes

Docker Compose with Nginx

Kubernetes Ingress

FastAPI deployment with root path:

Forwarded Headers

Access proxy forwarded headers in your application:
Be cautious with forwarded headers in security-sensitive applications. Validate that they’re coming from trusted proxies to prevent header injection attacks.

Testing Proxy Configuration

Test your configuration locally:

Common Pitfalls

Incorrect OpenAPI Schema URLs

If docs aren’t loading, check the root_path:

Mixed HTTP/HTTPS

Ensure proxies set X-Forwarded-Proto correctly:

Missing Host Headers

Best Practices

  • Always set root_path when behind a proxy with a path prefix
  • Configure proxies to forward X-Forwarded-* headers
  • Use environment variables for deployment-specific configuration
  • Test OpenAPI docs to verify proxy configuration
  • Implement proper logging to track the original client IP
  • Use SSL/TLS termination at the proxy for better performance
  • Validate forwarded headers come from trusted sources

Health Checks

Configure health check endpoints for load balancers:

See Also