Skip to main content

Module rewrite

Module rewrite 

Source
Expand description

Request and response rewriting middleware.

RewriteLayer is a Middleware that transforms requests before they reach handlers and responses before they leave the server. Build one with the fluent builder API and add it to any crate::middleware::WithMiddleware stack.

§Example

use rust_web_server::app::App;
use rust_web_server::core::New;
use rust_web_server::rewrite::RewriteLayer;

let app = App::new()
    .wrap(RewriteLayer::new()
        .request_header_set("X-Env", "production")
        .request_uri_strip_prefix("/api/v1")
        .response_header_set("Cache-Control", "no-store")
        .response_body_replace("http://staging.internal", "https://example.com"));

§Regex URI rewriting (rewrite-regex feature)

The prefix/set operations above cover fixed strings. When the rewrite depends on part of the incoming path — versioning schemes, locale prefixes, ID extraction — [RewriteLayer::request_uri_regex_rewrite] matches the URI against a regex and rewrites it using the match’s capture groups, the same rewrite semantics as nginx: if the pattern matches anywhere in the URI, the entire URI is replaced by the expanded replacement string; otherwise the URI is left untouched.

use rust_web_server::app::App;
use rust_web_server::core::New;
use rust_web_server::rewrite::RewriteLayer;

let app = App::new()
    .wrap(RewriteLayer::new()
        .request_uri_regex_rewrite(r"^/api/v\d+/(.*)$", "/$1")?);

Requires the rewrite-regex feature (adds the regex crate) — this is the one place in rws a third-party regex engine is worth the dependency; hand-rolling one is out of scope for this crate’s “no third-party HTTP dependencies” philosophy, which doesn’t extend to general-purpose text processing.

Structs§

RewriteLayer
Composable request/response rewriting middleware.