SERVERS · 3 NOV 2017 · 2 MIN READ

A trick to redirect PDF files to HTML pages in .htaccess

A trick to redirect PDF files in .htaccess without losing your mind.

Sometimes, as part of the changes and modifications we make on a website, we change the way PDF files or other static files are displayed, such as images, Word documents, etc. An example of this is when you used to publish the link to the PDF file directly and now you want to show it directly on an HTML page of your site, or you want to ask the visitor for some data before sending or allowing them to download the PDF file.

Trick to redirect PDF files to HTML pages in .htaccess

The first solution that comes to mind

It may have happened to you as it did to me: you said “this is very easy”, I’ll add a Redirect line in the .htaccess file of my hosting and problem solved, for example like this:

Redirect 301 /prueba/prueba.pdf https://www.prueba.com/prueba.html

but when we upload this new .htaccess file to the server, we see that if we call the PDF URL, it still returns the PDF.

The solution to redirect PDF files to HTML pages

The solution to this problem is very simple, but you have to figure it out: if the PDF file physically exists at the URL you type in your browser, Apache will always return this file, so all we have to do is delete the PDF file from our server or move it to a different directory, and from that moment the redirect will start working perfectly. Remember that if you move the file, you will have to go to your page and change the path to it.

I hope this little trick saves you quite a few headaches. The solution is very simple, but until you figure it out you can be searching on Google — as in my case, for almost an hour — for how to redirect PDF files to HTML pages in .htaccess without finding the solution.

 

Is this happening on a project in production?

We audit and fix WordPress and Laravel installations every week.

Let’s talk
Scroll to Top