On this page

Enforcing HTTPS in a FastAPI Deployment

Published on August 13, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Every request to an API carries something worth protecting — a password at login, a JWT on every later call, personal data in a response body — and none of that is safe in transit unless the connection carrying it is encrypted. Without HTTPS, anyone positioned to observe network traffic between a client and the server — a shared Wi-Fi network, a compromised router, an intermediary on the path — can read every one of those values in plain text. Getting HTTPS right in a FastAPI deployment isn't about FastAPI itself doing the encrypting; it's about understanding where that encryption actually happens, and making sure the pieces around FastAPI are configured to work with it correctly.


Why HTTPS Isn't Optional​

HTTPS uses TLS to encrypt traffic between a client and a server. Without it, a password, a JWT, or personal user data sent over the network is readable by anyone able to intercept that traffic — a real, practical risk on public Wi-Fi and shared infrastructure, not a theoretical one. Beyond the direct exposure risk, browsers actively mark plain HTTP sites as "Not Secure," and several browser-enforced behaviors — the Secure cookie attribute, and certain CORS interactions — simply don't function over plain HTTP at all.


Where TLS Actually Terminates​

FastAPI itself never handles a TLS handshake. It's an ASGI application that speaks plain HTTP to whatever process runs it — Uvicorn, most commonly. In a production deployment, a reverse proxy sits in front of the application and does the actual TLS work:


Client (HTTPS) → Reverse Proxy (TLS termination) → FastAPI (HTTP on localhost:8000)

This architecture is the standard approach across virtually every production FastAPI deployment, and for good reason: certificate management, cipher configuration, and protocol version enforcement are handled once, in one place, rather than duplicated across every backend process. FastAPI should never be exposed directly to the public internet without a reverse proxy in front of it.


Configuring the Reverse Proxy​

An NGINX configuration terminating TLS and forwarding to a local FastAPI process:


server {

    listen 443 ssl;

    server_name api.myapp.com;



    ssl_certificate /etc/letsencrypt/live/api.myapp.com/fullchain.pem;

    ssl_certificate_key /etc/letsencrypt/live/api.myapp.com/privkey.pem;



    # Modern TLS only

    ssl_protocols TLSv1.2 TLSv1.3;



    location / {

        proxy_pass http://127.0.0.1:8000;

        proxy_set_header Host $host;

        proxy_set_header X-Real-IP $remote_addr;

        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header X-Forwarded-Proto $scheme;

    }

}



# Redirect all HTTP to HTTPS

server {

    listen 80;

    server_name api.myapp.com;

    return 301 https://$host$request_uri;

}

ssl_protocols TLSv1.2 TLSv1.3 excludes older, weaker TLS versions from being negotiated at all. The second server block, listening on plain port 80, exists specifically to redirect any stray HTTP request to its HTTPS equivalent before it ever reaches the application.


Why X-Forwarded-Proto and X-Forwarded-For Matter​

Once NGINX forwards a request to FastAPI as plain HTTP on 127.0.0.1:8000, the application has no direct way to know the original request arrived over HTTPS, or what the real client's IP address was — from FastAPI's point of view, every request looks like it came from the proxy itself, over plain HTTP. X-Forwarded-Proto and X-Forwarded-For are how the proxy communicates that missing context, but Uvicorn doesn't trust these headers automatically from just anyone — a client could set them itself to lie about its own IP or protocol. Uvicorn's --proxy-headers option, enabled by default in current versions, only applies this trust to connections coming from IPs listed in --forwarded-allow-ips, which defaults to 127.0.0.1:


uvicorn main:app --proxy-headers --forwarded-allow-ips="127.0.0.1"

This default works cleanly when the reverse proxy runs on the same host as the FastAPI process. It does not work automatically when the proxy runs in a separate container or on a separate machine — in that case, --forwarded-allow-ips needs to explicitly list the proxy's actual address (or a trusted internal range), or the forwarded headers get ignored entirely regardless of what the proxy sends. Without this trust correctly configured, request.client.host returns the proxy's own address rather than the real client's — which silently breaks anything relying on the real IP, IP-based rate limiting in particular.


Enforcing HTTPS at the Application Level​

For cases where the application itself should enforce HTTPS — a proxy that might not handle the redirect on its own, for instance — FastAPI ships a built-in middleware that redirects any plain HTTP request to its HTTPS equivalent:


from fastapi import FastAPI

from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware



app = FastAPI()

app.add_middleware(HTTPSRedirectMiddleware)

Any http:// request receives a 307 Temporary Redirect to the https:// equivalent. This middleware should never be active in local development — without HTTPS configured locally, it breaks every request outright.

There's a specific, common failure mode worth understanding directly rather than discovering in production: deploying HTTPSRedirectMiddleware behind a reverse proxy without the proxy-headers trust configured correctly produces an infinite redirect loop, not a clean redirect. The middleware decides whether to redirect based on the scheme it sees on the incoming request — and if Uvicorn isn't trusting X-Forwarded-Proto from the proxy (because the proxy's IP isn't in --forwarded-allow-ips), every request still looks like plain HTTP to the middleware, even though the original client connection was genuinely HTTPS. The middleware redirects to HTTPS again, the proxy forwards that request the same way as before, and the loop repeats until the browser gives up with a "too many redirects" error. Getting --forwarded-allow-ips configured correctly for the actual proxy setup — same host versus separate container — is what resolves this, and it's worth checking before assuming HTTPSRedirectMiddleware itself is misbehaving.


Free Certificates with Let's Encrypt​

Let's Encrypt issues free, automatically renewable TLS certificates. On Ubuntu, Certbot handles both the issuance and the ongoing renewal:


sudo apt install certbot python3-certbot-nginx

sudo certbot --nginx -d api.myapp.com

Certbot modifies the NGINX configuration automatically and sets up a scheduled job to renew the certificate before it expires. The default certificate lifetime is currently 90 days, though Let's Encrypt has begun transitioning toward shorter-lived certificates industry-wide — a 45-day option is already available as an opt-in profile, with the default lifetime scheduled to shorten in stages over the next couple of years. A current version of Certbot (4.1.0 or later) uses ACME Renewal Information to adjust its renewal timing automatically regardless of which lifetime a certificate is actually issued with, which is one more reason to keep Certbot itself reasonably up to date rather than only worrying about the certificates it manages.

Key Takeaways​

FastAPI never terminates TLS itself — that's the job of a reverse proxy sitting in front of it, decrypting HTTPS traffic and forwarding plain HTTP to the application locally. Because of that split, the application only learns the real client IP and original protocol through X-Forwarded-For and X-Forwarded-Proto, and Uvicorn only trusts those headers from IPs explicitly listed in --forwarded-allow-ips — a detail that becomes essential the moment the proxy runs somewhere other than the same host as the application. HTTPSRedirectMiddleware adds a second layer of enforcement inside the application itself, but deploying it behind a reverse proxy without correctly configured proxy-header trust produces an infinite redirect loop rather than a clean redirect, since the middleware never sees evidence that the original connection was actually HTTPS. Let's Encrypt and Certbot together handle certificate issuance and renewal with minimal ongoing maintenance, and current Certbot versions already adapt automatically as the industry moves toward shorter certificate lifespans.

Frequently Asked Questions​

Why does request.client.host show my server's own IP instead of the real visitor's IP?

This happens when Uvicorn isn't configured to trust the reverse proxy's forwarded headers. By default, --proxy-headers only trusts X-Forwarded-For and X-Forwarded-Proto from connections originating at 127.0.0.1. If the proxy runs in a different container or on a different host, its IP needs to be added explicitly via --forwarded-allow-ips, or the real client IP will never be recovered.

I added HTTPSRedirectMiddleware and now my site gives a 'too many redirects' error. What's wrong?

This is almost always a proxy-header trust issue, not a problem with the middleware itself. If Uvicorn isn't trusting X-Forwarded-Proto from the reverse proxy's IP, every request still looks like plain HTTP to the middleware — even though the original client connection was HTTPS — so it keeps redirecting. Check that the proxy's IP is included in --forwarded-allow-ips.

Why does my local development server break as soon as I add HTTPSRedirectMiddleware?

HTTPSRedirectMiddleware redirects any request it doesn't recognize as HTTPS, and a local development server almost never has HTTPS configured. This middleware should only be active in a production environment where HTTPS is genuinely being served — not in local development.

Do I still need --forwarded-allow-ips if I'm only testing locally with no reverse proxy?

No. Proxy-header trust only matters once a reverse proxy sits in front of the application. Running Uvicorn directly with no proxy in front of it means request.client.host already reflects the real connecting client, and there's no forwarded header to trust or distrust.

Is it safe to set --forwarded-allow-ips="*" to avoid configuration issues?

Not in a real deployment. That setting trusts forwarded headers from any IP address, which means a malicious client could set its own X-Forwarded-For header and spoof any IP it wants — directly undermining anything relying on the real client address, including rate limiting. It should only be used when the application is airtight behind a proxy that can't be bypassed, and even then, listing the proxy's actual IP or internal network range is the safer choice.

My reverse proxy and FastAPI app run in separate Docker containers. What IP should I use for --forwarded-allow-ips?

Not 127.0.0.1 — that only covers a proxy running on the same host as the application. In a multi-container setup, the proxy connects from its own container's internal Docker network IP, which needs to be identified and added explicitly, rather than relying on the default.

Why did my TLS certificate suddenly need renewing sooner than the usual 90 days?

Let's Encrypt has begun a multi-year, industry-wide transition toward shorter certificate lifetimes — a 45-day option is already available as an opt-in profile, and the default lifetime is scheduled to shorten in stages over the next couple of years. Keeping Certbot updated to a current version lets it adjust its renewal timing automatically as this transition progresses, rather than assuming a fixed 90-day cycle indefinitely.

Certbot says it modified my NGINX config automatically — what exactly did it change?

Certbot adds the ssl_certificate and ssl_certificate_key directives pointing to the newly issued certificate files, and typically adds a redirect from HTTP to HTTPS if one wasn't already present. Reviewing the config file after running Certbot is worth doing at least once, so the specific changes made in a given setup are understood rather than left as a black box.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

CORS

Next

Rate Limiting