Trailing Slash

Middleware to automatically add or remove trailing slashes (/).

Use Cases

The Trailing Slash middleware is particularly useful in the following scenarios:

  • URL Normalization: Ensures all URLs adhere to a consistent format (either always adding or always removing the trailing slash), which helps improve SEO and avoid duplicate content issues.

  • Simplified Route Handling: Eliminates the need to write separate routing logic for paths with and without trailing slashes, as the middleware handles the transformation automatically.

  • Compatibility: Some clients might automatically add or remove trailing slashes from URLs. This middleware ensures that requests are routed correctly regardless.

  • Redirection Management: Can be configured to automatically redirect URLs with trailing slashes to their non-slashed counterparts (or vice versa), improving the user experience.

  • Avoiding Route Conflicts: In many web frameworks, /path and /path/ might be treated as distinct routes. This middleware unifies their handling.

Example Code

main.rs
Cargo.toml
trailing-slash/src/main.rs
use salvo::prelude::*;
use salvo::trailing_slash::add_slash;

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

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt().init();
    let router = Router::with_hoop(add_slash())
        .push(Router::with_path("hello").get(hello))
        .push(Router::with_path("hello.world").get(hello));
    let acceptor = TcpListener::new("0.0.0.0:5800").bind().await;
    Server::new(acceptor).serve(router).await;
}
On this page