user1024203 user1024203 - 3 months ago 14
Apache Configuration Question

.htaccess to allow only pdf files in a subdirectory

I am trying to write an

.htaccess
file to only allow access to pdf files in a subdirectory. I'm going to deploy the file on a host that I don't control, so I can't make changes to the apache configuration.

I want to only allow access to .pdf files in the
Foo
directory. I have attempted:

Deny From All

<FilesMatch ".+\/Foo\/.+\.pdf$">
Allow From All
</FilesMatch>


However, when I attempt to access
example.com/bar/Foo/baz.pdf
, I am given an HTTP 403 Forbidden response.

How can I deny access to everything, except for pdf files in one particular directory?

Thanks

Answer

Create a this inside root .htaccess as your very first rule:

RewriteEngine On

# prohibit everything except .pdf files    
RewriteRule ^foo/(?!.*\.pdf$) - [F,NC]