Wid9
Wid9

Reputation: 31

htaccess redirect path to pdf

I have a directory called /manuals which contains multiple PDF files.

What I'd like to achieve is to redirect and append a pdf extension to any URL which accesses this directory like so:

https://website.com/manuals/FM0100 to https://website.com/manuals/FM0100.pdf

Is this possible in a .htaccess file?

Upvotes: 1

Views: 456

Answers (2)

MrWhite
MrWhite

Reputation: 45829

In the /manuals/.htaccess file (ie. inside the /manuals subdirectory) you could do this:

RewriteEngine On

# Append ".pdf" to any request that does not already have a file extension.
RewriteRule !\.\w{2,4}$ %{REQUEST_URI}.pdf [R=302,L]

The request is externally redirected with a 302 - temporary - redirect.

Alternatively, you could internally rewrite the request (ie. .pdf extension hidden from user) by removing the R=302 flag.

The <IfModule> wrapper is not required.

Upvotes: 2

Wid9
Wid9

Reputation: 31

After experimenting I found a solution:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} manuals
RewriteCond %{REQUEST_URI} !pdf
RewriteCond %{REQUEST_URI} !png
RewriteCond %{REQUEST_URI} !jpg
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}.pdf

</IfModule>

Upvotes: 1

Related Questions