Properly Redirect Files and Directories with .htaccess

The Problem

A few days ago I was tasked to change the name of a directory containing PDF files linked to from many internal and external pages. Say you have a long list of links that go to important PDF files your visitors rely on.

  • http://example.com/files/pdf/important.pdf
  • http://example.com/files/pdf/safety.pdf
  • http://example.com/files/pdf/instructions.pdf

Now for whatever reason you need to change the file structure of the PDF files to something like http://example.com/documents/pdf/important.pdf. You might think all you need to do is change the file path and update all of your links on your site but... What if you have hundreds or thousands of pages linking to those files? What about external websites linking to your files? What about the links search engines have indexed?

The Solution

The solution is pretty simple depending on the number of directory changes you have. Let's assume we are replacing the files directory to documents. So our new links will be something like this:

  • http://example.com/documents/pdf/important.pdf
  • http://example.com/documents/pdf/safety.pdf
  • http://example.com/documents/pdf/instructions.pdf

On our .htaccess file we now add this line of code:

RewriteRule ^files/pdf/(.*)$ /documents/pdf/$1 [R=301,NC,L]

What this does is that any URL matching anything with /files/pdf/ and after that will be redirected to /documents/pdf/ along with it's parameters. So then http://example.com/files/pdf/important.pdf will be redirected to http://example.com/documents/pdf/important.pdf and so on.

Edgar Pino

About Edgar Pino

I’m a passionate software engineer. I currently work at Envano Interactive on application backends, server management, and finding solutions to technological challenges our clients face.

Comments