Force HTTPS
force-https
middleware can force all requests to use the HTTPS protocol.
If this middleware is applied to Router
, the protocol will be forced to convert only when the route is matched. If the page does not exist, it will not be redirected.
But a more common requirement is to expect any request to be automatically redirected, even when the route fails to match and returns a 404
error. At this time, you can add the middleware to Service
. Regardless of whether the request is successfully matched by the route, the middleware added to Service
will always be executed.
Sample code
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;
}
[package]
name = "example-force-https"
version.workspace = true
edition.workspace = true
publish.workspace = true
[dependencies]
salvo = { workspace = true, features = ["rustls", "force-https"] }
tokio = { workspace = true, features = ["macros"] }
tracing.workspace = true
tracing-subscriber.workspace = true