2019-11-18 05:58:33 +01:00
|
|
|
---
|
2014-10-18 00:28:51 +02:00
|
|
|
title: Redirection
|
|
|
|
summary: Move users around your site using automatic redirection.
|
2019-11-18 05:58:33 +01:00
|
|
|
icon: reply
|
|
|
|
---
|
2014-10-18 00:28:51 +02:00
|
|
|
|
|
|
|
# Redirection
|
|
|
|
|
|
|
|
Controllers can facilitate redirecting users from one place to another using `HTTP` redirection using the `Location`
|
|
|
|
HTTP header.
|
|
|
|
|
2018-06-25 00:39:53 +02:00
|
|
|
**app/code/Page.php**
|
2014-10-18 00:28:51 +02:00
|
|
|
|
2017-08-03 02:51:32 +02:00
|
|
|
|
|
|
|
```php
|
2017-10-27 04:38:27 +02:00
|
|
|
$this->redirect('goherenow');
|
|
|
|
// redirect to Page::goherenow(), i.e on the contact-us page this will redirect to /contact-us/goherenow/
|
2014-10-18 00:28:51 +02:00
|
|
|
|
2017-10-27 04:38:27 +02:00
|
|
|
$this->redirect('goherenow/');
|
|
|
|
// redirect to the URL on yoursite.com/goherenow/. (note the trailing slash)
|
2014-10-18 00:28:51 +02:00
|
|
|
|
2017-10-27 04:38:27 +02:00
|
|
|
$this->redirect('http://google.com');
|
|
|
|
// redirect to http://google.com
|
2014-10-18 00:28:51 +02:00
|
|
|
|
2017-10-27 04:38:27 +02:00
|
|
|
$this->redirectBack();
|
|
|
|
// go back to the previous page.
|
2017-08-03 02:51:32 +02:00
|
|
|
```
|
2014-10-18 00:28:51 +02:00
|
|
|
|
|
|
|
## Status Codes
|
|
|
|
|
|
|
|
The `redirect()` method takes an optional HTTP status code, either `301` for permanent redirects, or `302` for
|
|
|
|
temporary redirects (default).
|
2017-10-27 04:38:27 +02:00
|
|
|
|
2017-08-03 02:51:32 +02:00
|
|
|
```php
|
2017-10-27 04:38:27 +02:00
|
|
|
$this->redirect('/', 302);
|
|
|
|
// go back to the homepage, don't cache that this page has moved
|
2017-08-03 02:51:32 +02:00
|
|
|
```
|
2014-10-18 00:28:51 +02:00
|
|
|
|
|
|
|
## Redirection in URL Handling
|
|
|
|
|
|
|
|
Controllers can specify redirections in the `$url_handlers` property rather than defining a method by using the '~'
|
|
|
|
operator.
|
|
|
|
|
2017-08-03 02:51:32 +02:00
|
|
|
```php
|
2017-10-27 04:38:27 +02:00
|
|
|
private static $url_handlers = [
|
|
|
|
'players/john' => '~>coach'
|
|
|
|
];
|
2017-08-03 02:51:32 +02:00
|
|
|
```
|
2014-10-18 00:28:51 +02:00
|
|
|
|
|
|
|
For more information on `$url_handlers` see the [Routing](routing) documenation.
|
|
|
|
|
|
|
|
## API Documentation
|
|
|
|
|
2017-07-03 03:22:12 +02:00
|
|
|
* [Controller](api:SilverStripe\Control\Controller)
|