Usage | laravel-missing-page-redirector-rust | Spatie       

 SPATIE  

laravel-missing-page-redirector-rust
====================================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-missing-page-redirector-rust](https://spatie.be/docs/laravel-missing-page-redirector-rust/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-missing-page-redirector-rust/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/laravel-missing-page-redirector-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-missing-page-redirector-rust/v1/support-us)
- [ Installation ](https://spatie.be/docs/laravel-missing-page-redirector-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-missing-page-redirector-rust/v1/usage)
- [ Testing ](https://spatie.be/docs/laravel-missing-page-redirector-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-missing-page-redirector-rust/v1/changelog)

 Usage
=====

###  On this page 

1. [ Rules ](#content-rules)
2. [ Application configuration ](#content-application-configuration)
3. [ Dynamic providers ](#content-dynamic-providers)
4. [ Events ](#content-events)
5. [ External destinations and loops ](#content-external-destinations-and-loops)
6. [ Errors ](#content-errors)

Rules
-----------------------------------------------------------------------

```
use laravel::http::StatusCode;
use spatie_missing_page_redirector::{RedirectRule, RedirectRules};

let rules = RedirectRules::new([
    RedirectRule::new("/old", "/new")?,
    RedirectRule::new("/posts/{id}-{slug}", "/posts/{id}/{slug}")?,
    RedirectRule::new("/archive/*", "/articles/{wildcard}")?,
    RedirectRule::new("/temporary", "/current")?
        .status(StatusCode::TEMPORARY_REDIRECT)?
        .preserve_query(true),
]);
```

- Rules match the original percent-encoded path, case-sensitively. The first matching rule wins. Trailing slashes are significant.
- A named parameter matches one nonempty segment. Names start with an ASCII letter and contain only letters, numbers and underscores.
- One `*` captures a path, including slashes, as `{wildcard}`. It can precede a literal suffix, such as `/archive/*/edit`.
- `/old/{one?}/{two?}` accepts zero, one or two trailing segments. Missing parameters remove their preceding slash in the target.
- Targets are root-relative paths or absolute HTTP(S) URLs. Encode spaces, non-ASCII characters and literal braces before constructing a rule.
- Captures are inserted once, without decoding or re-encoding. Parameters cannot change an absolute target's origin.
- Redirect status can be 301, 302, 303, 307 or 308. The default is 301.
- Source patterns never include queries. Incoming queries are dropped by default. `preserve_query(true)` retains their bytes, including repeated keys, only when the target has no query. A configured query always wins; fragments stay after the query.
- Cloning `RedirectRules` shares immutable rules rather than copying every pattern.

Application configuration
-----------------------------------------------------------------------------------------------------------------------------------

- Register `service_provider()` to load environment-backed defaults through package-tools.
- Override rules in `with_config`. `ConfigurationRedirector` reads them after each eligible response.
- A custom `Redirector` uses the same response-status policy.

```
use laravel::Application;
use spatie_missing_page_redirector::{
    Config, ConfigurationRedirector, RedirectRule, RedirectRules, RedirectsMissingPages,
    service_provider,
};
let rules = RedirectRules::new([RedirectRule::new("/old", "/new")?]);
let redirector = RedirectsMissingPages::new(ConfigurationRedirector, "https://example.com")?;
let app = Application::configure()
    .with_providers(|providers| { providers.add(service_provider()); })
    .with_config(move |config, _| {
        config.set(Config {
            redirects: rules,
            ..config.section::<Config>().clone()
        });
    })
    .with_middleware(move |middleware, _| { middleware.append(redirector); })
    .create();
```

- `enabled` defaults to `true`. Set `MISSING_PAGE_REDIRECTOR_ENABLED=false` to skip lookup and events.
- `redirect_status_codes` defaults to `[StatusCode::NOT_FOUND]`. `MISSING_PAGE_REDIRECTOR_STATUS_CODES=418,500` selects those responses instead of 404.
- An empty typed status list allows every response status, including 200. Set `MISSING_PAGE_REDIRECTOR_STATUS_CODES=all` for this behavior. This intentionally lets matching rules replace existing pages. Blank environment values use the default 404 filter, following the framework's environment rules.
- `redirects` defaults to an empty ordered rule set. Configure rules in code; the environment selects policy, not executable provider types.
- Invalid environment values fail native application validation at startup.
- Without a config section, static rules and custom providers retain the default 404-only policy.
- `ConfigurationRedirector` requires its section. Register the provider or set `Config::from_env(env)` explicitly. Missing configuration returns `Error::MissingConfiguration` through the framework error handler.
- Methods other than GET and HEAD never redirect, regardless of configuration.

Dynamic providers
-----------------------------------------------------------------------------------------------------------

- The framework calls the provider only after an eligible GET or HEAD response. Query application data here so edits take effect without restarting the application.
- Return a slug rule first when an old article slug exists; otherwise build rules from current redirect rows.
- Keep rules anchored to the full path so `/old-slug/extra` cannot redirect as `/old-slug`.
- This example uses in-memory data. Replace the lookup with an awaited database query without changing the middleware.

```
use spatie_missing_page_redirector::{
    RedirectRequest, RedirectRule, RedirectRules, Redirector, RedirectsMissingPages,
};

#[derive(Debug)]
struct LegacyUrls;

impl Redirector for LegacyUrls {
    async fn redirects(&self, request: &RedirectRequest) -> laravel::Result<RedirectRules> {
        let slug = request.path().trim_start_matches('/').split('/').next();
        let old_post = match slug {
            Some("old-title") => Some(("/old-title", "/42-current-title")),
            _ => None,
        };
        if let Some((old, current)) = old_post {
            return Ok(RedirectRules::new([RedirectRule::new(old, current)?]));
        }
        let rows = [("/old-page", "/current-page")];
        let rules = rows.into_iter()
            .map(|(old, new)| RedirectRule::new(old, new))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(RedirectRules::new(rules))
    }
}

let redirector = RedirectsMissingPages::new(LegacyUrls, "https://example.com")?;
let app = laravel::Application::configure()
    .with_middleware(move |middleware, _| { middleware.append(redirector); })
    .create();
```

- `RedirectRequest::path()` and `query()` contain no request headers, body or trusted origin.
- Provider errors go to the framework's error handler rather than becoming silent misses.
- No database models are required. Register `service_provider()` only if you want environment-backed policy defaults.

Events
--------------------------------------------------------------------------

- Register native listeners with the application's `with_events` hook:

```
use laravel::event::Event;
use spatie_missing_page_redirector::events::RouteWasHit;

async fn record_redirect(event: Event<RouteWasHit>) {
    assert_eq!(event.route, "/new");
    assert_eq!(event.missing_url, "/old");
    assert_eq!(event.status_code.as_u16(), 301);
}

let app = laravel::Application::configure()
    .with_events(|events, _| { events.listen(record_redirect); })
    .create();
```

- `RouteWasHit` contains the resolved `route`, original source pattern in `missing_url`, and effective redirect `status_code`.
- `RedirectNotFound` contains the encoded path and raw query in `request`. It fires when an eligible lookup has no usable redirect, including a blocked external destination or detected loop.
- Ineligible responses and unsafe methods dispatch neither event. Storage/provider errors propagate and do not dispatch a miss.
- Listener errors propagate through the framework's error handler; they are not swallowed.
- Use `laravel::event::fake()` with `assert_dispatched_where` in `#[laravel::test]` application tests to inspect event payloads without running listeners.

External destinations and loops
-----------------------------------------------------------------------------------------------------------------------------------------------------

```
let rules = RedirectRules::new([
    RedirectRule::new("/reference", "https://docs.example.org/guide?version=2")?,
]);
let redirector = RedirectsMissingPages::new(rules, "https://example.com")?
    .allow_external_origin("https://docs.example.org")?;
```

- Without an allowlist entry an external target leaves the original response intact. Origins include scheme and port.
- Incoming Host, Forwarded and X-Forwarded-Host headers never authorize external redirects. Configure the framework's trusted-host middleware too; this package does not replace it.
- Treat database rules as trusted administrator configuration, not arbitrary user-submitted URLs.
- Self-redirects are suppressed, including normalized dot segments, fragments and canonical absolute URLs.
- The middleware checks up to 32 same-origin hops to reject cycles and nonterminating wildcard expansions. Locations longer than 8192 bytes are rejected, including during this check.
- The check uses only the returned rule set, without HTTP requests. The actual redirect retains its first-hop status and location. Remove stale rules; a conflict can be rejected even if an intermediate path has a working route.
- Cycles split between request-dependent rule sets or external sites cannot be detected. The middleware neither queries other provider states nor fetches external sites.
- An unsafe target rejected after capture substitution leaves the original response intact.

Errors
--------------------------------------------------------------------------

- Rule and middleware constructors return this crate's `Error`. Use `?` or match the variants when configuration comes from user input.
- `InvalidRule` contains a malformed pattern or a target with invalid parameter references. `InvalidTarget` contains an unsafe destination.
- `InvalidStatus` contains the unsupported HTTP status. `InvalidOrigin` contains an invalid canonical or external origin.
- `MissingConfiguration` means `ConfigurationRedirector` has no `Config` section. Register `service_provider()` or set the section explicitly.
- Provider and event-listener failures propagate as `laravel::Error`, not redirect misses. Wrapped configuration errors remain available through `downcast_ref::<Error>()`.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
