Function actix_web::guard::Host

source ·
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.

Examples

The Host guard can be used to set up a 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 127.0.0.1 and localhost as the Host guards.

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

App::new()
    .service(
        web::scope("")
            .guard(guard::Host("www.rust-lang.org"))
            .default_service(web::to(|| async {
                HttpResponse::Ok().body("marketing site")
            })),
    )
    .service(
        web::scope("")
            .guard(guard::Host("play.rust-lang.org"))
            .default_service(web::to(|| async {
                HttpResponse::Ok().body("playground frontend")
            })),
    );

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};

web::scope("/admin")
    .guard(Host("admin.rust-lang.org").scheme("https"))
    .default_service(web::to(|| async {
        HttpResponse::Ok().body("admin connection is secure")
    }));