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

 SPATIE  

laravel-missing-page-redirector-go
==================================

spatie.be/open-source

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

 Version   v1      

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

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

 Usage
=====

###  On this page 

1. [ Creating redirects ](#content-creating-redirects)
2. [ Response status codes ](#content-response-status-codes)
3. [ Matching and destinations ](#content-matching-and-destinations)
4. [ Loops ](#content-loops)
5. [ Events ](#content-events)
6. [ Creating your own redirector ](#content-creating-your-own-redirector)
7. [ If you want to use a fallback handler ](#content-if-you-want-to-use-a-fallback-handler)

Creating redirects
--------------------------------------------------------------------------------------------------------------

Creating a redirect is easy. Add an entry to `Redirects` in the callback passed to `redirector.New`:

```
c.Redirects = redirector.Rules{
    {From: "/non-existing-page", To: "/existing-page"},
}
```

You may use route parameters like you are used to with Laravel routes:

```
c.Redirects = redirector.Rules{
    {From: "/old-blog/{url}", To: "/new-blog/{url}"},
    {From: "/posts/{id}-{slug}", To: "/articles/{id}/{slug}"},
}
```

Optional parameters are also an option:

```
c.Redirects = redirector.Rules{
    {From: "/old-blog/{url?}", To: "/new-blog/{url}"},
    {From: "/archive/{year?}/{month?}", To: "/articles/{year}/{month}"},
}
```

Optional parameters must occupy trailing segments. Missing parameters remove their preceding slash in the destination. Names start with an ASCII letter and contain letters, digits or underscores. Names cannot repeat within a pattern.

Finally, use an asterisk as a wildcard parameter that matches multiple URL segments:

```
c.Redirects = redirector.Rules{
    {From: "/old-blog/*", To: "/new-blog/{wildcard}"},
}
```

The wildcard can precede a literal suffix, such as `/archive/*/edit`. At most one wildcard is allowed.

Response status codes
-----------------------------------------------------------------------------------------------------------------------

By default the package only redirects GET and HEAD requests with a 404 response. To select other response codes:

```
c.StatusCodes = []int{418, 500}
```

Use `[]int{}` to redirect regardless of the response code, including existing 200 pages. Use `nil` to disable lookups and events entirely. Other HTTP methods never redirect.

The default redirect status is 301 Moved Permanently. Override it per rule:

```
c.Redirects = redirector.Rules{
    {From: "/old-page", To: "/new-page", Status: 302},
}
```

Supported redirect statuses are 301, 302, 303, 307 and 308.

Matching and destinations
-----------------------------------------------------------------------------------------------------------------------------------

Rules are checked in slice order. The first match wins. Matching is anchored to the whole path, case-sensitive and percent-encoded. Source paths accept an omitted leading slash and an optional trailing slash. Named parameters match one nonempty segment. Query strings do not participate in matching and are not copied to the destination.

Destinations must be root-relative paths or absolute HTTP(S) URLs. Configured queries, fragments and trailing slashes are preserved exactly. Captured values are inserted once without decoding or re-encoding. Unresolved `/{name}` destination segments are removed, matching PHP's behavior. Literal braces, spaces and non-ASCII bytes must be percent-encoded. Do not put optional markers or asterisks in destination placeholders, use `{name}` and `{wildcard}` instead.

Configured external destinations are allowed without a separate allowlist, as in PHP. Treat rules as trusted administrator configuration, not arbitrary user input. Captures cannot change an absolute destination's host. Protocol-relative URLs, credentials, backslashes, control characters and unsafe schemes are rejected.

Static invalid rules fail startup. Invalid dynamic rules and provider errors reach Laravel's error handler. Unsafe destinations produced by substitution leave the original response unchanged. No-match responses retain their original status, headers and body.

Loops
-----------------------------------------------------------------------

The package suppresses self-redirects, cycles, nonterminating wildcard expansion and chains of 32 or more same-origin rule applications. It checks only the returned rules, without making HTTP requests or querying the custom redirector again. The actual response retains the first hop's location and status.

Set Laravel's `APP_URL` correctly for same-origin checks. Incoming Host or forwarded headers do not authorize a different origin. Cycles across external sites or different request-dependent rule sets cannot be detected. A rule conflict can be suppressed even if an intermediate path has a working application route, so remove stale rules.

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

The package fires `redirector.RouteWasHit` when it finds a usable redirect. It contains `Route`, `MissingURL` and `StatusCode`. A `redirector.RedirectNotFound` fires when no usable redirect was found, including suppressed loops or unsafe substitutions. Its `Request` contains `Path` and raw `Query`, without a live body or headers.

Register native listeners with `laravel.Listen`:

```
Listeners: []laravel.Listener{
    laravel.Listen(func(ctx context.Context, e redirector.RouteWasHit) error {
        slog.InfoContext(ctx, "Redirected legacy URL", "from", e.MissingURL, "to", e.Route)
        return nil
    }),
},
```

Ineligible responses and unsafe methods fire neither event. Provider and listener failures propagate rather than becoming silent misses. Unlike PHP's broad exception catch, errors remain distinguishable from missing redirects.

Creating your own redirector
--------------------------------------------------------------------------------------------------------------------------------------------

By default this package gets its redirects from `Config.Redirects`. To use another source, such as a database, implement the `Redirector` interface:

```
type Redirector interface {
    GetRedirectsFor(ctx context.Context, request *http.Request) (redirector.Rules, error)
}
```

The method returns an ordered slice of old path patterns and new destinations. The package calls it only after eligible responses. Use the supplied context for database queries and cancellation. `request` is the original HTTP request, so you can select rules by host, query or headers. Do not retain it after the request finishes.

For short implementations, adapt a function:

```
c.Redirector = redirector.RedirectorFunc(func(ctx context.Context, request *http.Request) (redirector.Rules, error) {
    if request.Header.Get("X-Legacy-Site") == "yes" {
        return redirector.Rules{{From: "/old", To: "/new"}}, nil
    }
    return nil, nil
})
```

The configured custom source replaces static rules completely. Query current data here to apply database changes without restarting. The package does not impose a model or storage layer. Your implementation owns synchronization for shared mutable data. Explicit `Config.Redirector` injection also avoids Laravel Go v0.1.0's first-registration-wins service lookup behavior.

If you want to use a fallback handler
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

If you already have fallback logic, set `Config.DisableMiddleware = true`. In your fallback handler:

```
res, err := redirector.From(r).GetRedirectFor(r)
if err != nil {
    return web.Fail(err)
}
if res != nil {
    return res
}
return web.Abort(404)
```

`r` is the handler's `*web.Request`. You choose where the redirect lookup belongs relative to your other fallback logic. A miss returns `(nil, nil)`. This explicit lookup ignores the response-status filter, but still respects disabled lookups and only handles GET and HEAD.

 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)
