PWaddict

Redirect broken image / file urls to their pages

Recommended Posts

Let's say that you have an image called myimage.jpg and it's accessible via http://localhost/mysite/site/assets/files/1020/myimage.jpg. If you rename or delete that image and users keep visiting that link they will obviously view a 404 error page.

Instead of displaying the 404 error page you can redirect them to the file's belonging page by adding the below code on top of your 404.php template:

$url = $_SERVER["REQUEST_URI"];
$pattern = "@site/assets/files/(\d+)/@";

if (preg_match($pattern, $url, $pageid)) {
  $fp = $pages->get($pageid[1]); // get the page id from the file path
  if($fp instanceof RepeaterPage) $fp = $fp->getForPage(); // if the file is inside repeater item get the page where the repeater belongs
  if($fp->viewable()) $session->redirect($fp->url, false); // redirect only if the page is viewable
  // false = 302 temporary redirect - true = 301 permanent redirect
}

 

  • Like 2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.