Fook
Fook

Reputation: 5550

Restrict access to a directory by file type

My Google-fu is failing me on this one...

I'm trying to create an Apache config that will only allow access to image, js, and css files in a specific directory.

For example, the following URL should work:

mysite.com/dir/image.gif

but this should be blocked:

mysite.com/dir/page.php

The part I'm struggling with is getting it working only for /dir/. The rest of the directories outside of /dir/ shouldn't be impacted by this directive.

This is what I have so far, which isn't doing what I need (it seems to apply to all directories).

<FilesMatch "\.(gif|jpe?g|jpg|png|js|css)$">
  Order deny,allow
  Allow from all
</FilesMatch>

How do I only allow access to certain file types within /dir/ but not affect the rest of my directories?

Upvotes: 2

Views: 10631

Answers (3)

jeffatrackaid
jeffatrackaid

Reputation: 346

I recently used this:

Options -ExecCGI -Indexes
<FilesMatch "\.*$">
deny from all
</FilesMatch>
<FilesMatch "\.(png|jpg|gif|css)$">
allow from all
</FilesMatch>

I could not find explicit documentation on this but for FilesMatch it appears Apache does not short-circuit at the first match. It processes the entire .htaccess rules.

So the first rule blocks access to all file types and the second then allows the selected types.

Probably needs more testing but had to do something for a client that was easy for them to implement to deal with a web exploit their developers are struggling to fix.

Upvotes: 4

Daniel
Daniel

Reputation: 1406

For simplicity, when I do this I usually put all the media files in their own directory. However if this isn't an option you might try the FilesMatch directive:

http://httpd.apache.org/docs/2.2/mod/core.html#filesmatch

You can put a FilesMatch inside a Directory.

Upvotes: 3

SpliFF
SpliFF

Reputation: 38966

I'd generally use mod_rewrite for that

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} ^/my_dir/[^/]+\.php$
RewriteRule .* - [F]

Upvotes: 0

Related Questions