SilverStripe Redirect on Page Errors

There are times in which you want to redirect users to a specific section of the site on page errors, for example, you may wish to redirect all requests to old URL pre site go live to the home page.  Here we discuss adding a request filter that will catch all page errors and redirect the user to the home page.

  1. Add page extension in site config
    ~/mysite/_config/config.php
    // Handle page not found errors by redirecting to home page
    Object::add_extension('Page', 'PageNotFoundExtension');
  2. Add request filter in site config
    ~/mysite/_config/config.yml
    Injector:
      RequestProcessor:
        properties:
          filters:
            - '%$PageNotFoundExtension'
  3. Create your new extension class
    <?php
    
    class PageNotFoundExtension extends DataExtension implements RequestFilter {
    
    	public function contentControllerInit( $controller ) {
    	}
    
    	public function preRequest( SS_HTTPRequest $request, Session $session, DataModel $model ) {
    	}
    
    	public function postRequest( SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model ) {
    		if  ( $response->isError() ) {
    			$response->redirect( Director::BaseURL() );
    		}
    	}
    
    }
  4. Dev build your site
    yoursite.com/dev/build?flush=1

References
https://docs.silverstripe.org/en/3.1/developer_guides/controllers/requestfilters/