pub fn Host(host: impl AsRef<str>) -> HostGuard
Expand description

Creates a guard that matches requests targetting a specific host.

Matching Host

This guard will:

  • match against the Host header, if present;
  • fall-back to matching against the request target’s host, if present;
  • return false if host cannot be determined;

Matching Scheme

Optionally, this guard can match against the host’s scheme. Set the scheme for matching using Host(host).scheme(protocol). If the request’s scheme cannot be determined, it will not prevent the guard from matching successfully.


The module-level documentation has an example of virtual hosting using Host guards.

The example below additionally guards on the host URI’s scheme. This could allow routing to different handlers for http: vs https: visitors; to redirect, for example.

use actix_web::{web, guard::Host, HttpResponse};

    .default_service(web::to(|| async {
        HttpResponse::Ok().body("admin connection is secure")

The Host guard can be used to set up some form of virtual hosting within a single app. Overlapping scope prefixes are usually discouraged, but when combined with non-overlapping guard definitions they become safe to use in this way. Without these host guards, only routes under the first-to-be-defined scope would be accessible. You can test this locally using and localhost as the Host guards.

use actix_web::{web, http::Method, guard, App, HttpResponse};

            .default_service(web::to(|| async {
                HttpResponse::Ok().body("marketing site")
            .default_service(web::to(|| async {
                HttpResponse::Ok().body("playground frontend")