allowed_hosts

class litestar.middleware.allowed_hosts.AllowedHostsMiddleware[source]

Bases: ASGIMiddleware

Middleware ensuring the host of a request originated in a trusted host.

__init__(*, allowed_hosts: list[str] | None = None, exclude: str | list[str] | None = None, exclude_opt_key: str | None = None, scopes: Scopes | None = None, www_redirect: bool = True) None[source]

Initialize AllowedHostsMiddleware.

Parameters:
  • allowed_hosts – A list of trusted hosts. Use * to allow all hosts, or prefix domains with *. to allow all subdomains. Wildcard placement is validated by AllowedHostsConfig, not here.

  • exclude – A pattern or list of patterns to skip.

  • exclude_opt_key – An identifier to use on routes to disable the host check for a particular route.

  • scopes – ASGI scopes processed by the middleware; if None or empty, http, websocket and ASGI route handlers are all processed. Mounted ASGI apps stay wrapped regardless, with their connections filtered by scope type.

  • www_redirect – A boolean dictating whether to redirect requests that start with www. and otherwise match a trusted host.

classmethod from_config(config: AllowedHostsConfig) AllowedHostsMiddleware[source]

Create an instance from an AllowedHostsConfig.

async handle(scope: Scope, receive: Receive, send: Send, next_app: ASGIApp) None[source]

Handle ASGI call.

Parameters:
  • scope – The ASGI connection scope.

  • receive – The ASGI receive function.

  • send – The ASGI send function.

  • next_app – The next ASGI application in the middleware stack to call.

Returns:

None