Redirect PDF File Only When Missing

PDF-icon.png

redirect PDF file when missingWe have a client that has hundreds of training and product manuals and many have been removed over time.  That creates broken links and frustrated customers for them.  They had two folders that these resided in, /images/documents/ and /im_uploads/

We recommend creating a new page with a specific message that the resource is missing and then adding a search form and links to browse.  In the example below, we made such a page with a url of https://www.mysite.com/missing-file

To redirect we put together this htaccess redirect:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/images/documents/.* [NC,OR]
RewriteCond %{REQUEST_URI} ^/im_uploads/.* [NC]
RewriteRule ^(.*)\.pdf$ https://www.mysite.com/missing-file [L,R=301]

 

It first checks if the url being tested is an actual file or directory.  This is important so that we do not redirect working files. 

The next two lines confine this to the two folders we want to check because we don’t want to be affecting things in the media folder or whatnot.  If you only need to check one folder, make sure you remove the OR from the end of the line you keep.  The [NC] makes the match case insensitive which we used because there were many variants of the file names and wanted to catch them all.

The rule line tells it to take all the pdf files (you can modified to another file extension for other uses) and then redirect to the new page we setup.  The [L] means it is the last rule and it should “exit” out of the htaccess and not apply any other rules.  The [R=301] is very important for SEO because it tells search engines that it is a permanent redirect.

About YellowWebMonkey

YellowWebMonkey Web design offers reliable website design, SEO and digital marketing services for Joomla, WordPress and Shopify sites. We strive to be a one-stop shop for all your web needs.

Recent Posts

Follow Us