Jump to content

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:

$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 3

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Create New...