Skip to main content
The TrustedHostMiddleware class validates incoming HTTP Host headers against a list of allowed hosts. This helps prevent host header injection attacks and ensures requests are only processed for valid domains.

Parameters

allowed_hosts
list[str] | None
default:"[\"*\"]"
List of allowed host values. Use ["*"] to allow all hosts (not recommended for production). Can include port numbers.
allowed_hosts=["example.com", "www.example.com", "api.example.com"]
www_redirect
bool
default:"true"
Whether to redirect non-www hosts to their www equivalent when the www version is in the allowed hosts list.
www_redirect=True

Usage

from fastrapi import FastrAPI
from fastrapi.middleware import TrustedHostMiddleware

app = FastrAPI()

app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["127.0.0.1", "localhost", "127.0.0.1:8000"],
    www_redirect=True
)

Examples

Development configuration

from fastrapi import FastrAPI
from fastrapi.middleware import TrustedHostMiddleware

app = FastrAPI()

app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["127.0.0.1", "localhost", "127.0.0.1:8000"],
    www_redirect=True
)

Production configuration

app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=[
        "example.com",
        "www.example.com",
        "api.example.com"
    ],
    www_redirect=True
)
app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["*"],
    www_redirect=False
)

Multiple environments with port numbers

import os

app = FastrAPI()

if os.getenv("ENV") == "production":
    allowed_hosts = ["example.com", "www.example.com"]
else:
    allowed_hosts = ["localhost", "127.0.0.1", "localhost:8000", "127.0.0.1:8000"]

app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=allowed_hosts,
    www_redirect=True
)

Build docs developers (and LLMs) love