Force HTTPS

The force-https middleware can redirect all requests to use the HTTPS protocol.

If this middleware is applied to a Router, it will only enforce protocol redirection when the route is matched. If the page does not exist, no redirection will occur.

However, a more common requirement is to automatically redirect any request, even when the route fails to match and returns a 404 error. In such cases, the middleware can be added to the Service. Regardless of whether the request matches a route successfully, middleware added to the Service will always be executed.

Example Code

main.rs
Cargo.toml
force-https/src/main.rs
use salvo::conn::rustls::{Keycert, RustlsConfig};
use salvo::prelude::*;

#[handler]
async fn hello() -> &'static str {
"Hello World"
}

#[tokio::main]
async fn main() {
tracing_subscriber::fmt().init();

let router = Router::new().get(hello);
let service = Service::new(router).hoop(ForceHttps::new().https_port(5443));

let config = RustlsConfig::new(
    Keycert::new()
        .cert(include_bytes!("../certs/cert.pem").as_ref())
        .key(include_bytes!("../certs/key.pem").as_ref()),
);
let acceptor = TcpListener::new("0.0.0.0:5443")
    .rustls(config)
    .join(TcpListener::new("0.0.0.0:5800"))
    .bind()
    .await;
Server::new(acceptor).serve(service).await;
}