Skip to main content

https_redirect

Function https_redirect 

Source
pub async fn https_redirect(
    __arg0: State<TrustedProxies>,
    req: Request,
    next: Next,
) -> Response
Expand description

Middleware that redirects plain-HTTP requests to HTTPS.

TLS terminates at a reverse proxy, so plain HTTP is detected through the X-Forwarded-Proto header (first value of a comma-separated list, case-insensitive). When it is http, the response is a 308 Permanent Redirect to https://{host}{path_and_query}, which keeps the method and body. The host comes from X-Forwarded-Host, falling back to Host. Requests without X-Forwarded-Proto (probes, worker traffic) and requests with no usable host pass through untouched.

Forwarding headers are client input unless a proxy overwrote them, so they are read only when the TCP peer is in TrustedProxies. The peer comes from ConnectInfo<SocketAddr>, so the router must be served with into_make_service_with_connect_info::<SocketAddr>(). A request from any other peer, or without connect info, passes through untouched: with an empty TrustedProxies, nothing is ever redirected.

ยงExamples

use axum::Router;
use axum::middleware::from_fn_with_state;
use axum::routing::get;
use ironflow_api::middleware::https_redirect;
use ironflow_api::rate_limit::TrustedProxies;

let app: Router = Router::new()
    .route("/", get(|| async { "ok" }))
    .layer(from_fn_with_state(TrustedProxies::default(), https_redirect));