Stevko
Stevko

Reputation: 4495

How to hide certain file type using apache .htaccess?

Its been a long time since I've needed to crack open an .htaccess file...

What is the simplest way to 40x prevent access to a specific file extension through out the entire site?

Upvotes: 18

Views: 25116

Answers (6)

arobson13
arobson13

Reputation: 69

@Dário has the right idea for File Types, and it can also be used for specific files and directories as well. The only thing that is missing is to manage case sensitivity.

I came across this article that gives some detail about case-sensitive RedirectMatch, and also suggests being character case non-sensitive.

When it comes to redirecting most requests, its all lowercase anyway. Or you can use RewriteRule to establish case-insensitivity. But for some situations, it’s good to know that you can also roll with RedirectMatch by simply adding the (?i) to the rule.

RedirectMatch 403 /\$\&
RedirectMatch 403 (?i)/\.(bash|git|hg|log|svn|swp|tar)
RedirectMatch 403 (?i)/(1|contact|i|index1|iprober|phpinfo|phpspy|product|signup|t|test|timthumb|tz|visit|webshell|wp-signup).php
RedirectMatch 403 (?i)/(author-panel|class|database|manage|phpMyAdmin|register|submit-articles|system|usage|webmaster)/?$
RedirectMatch 403 (?i)/(=|_mm|cgi|cvs|dbscripts|jsp|rnd|userfiles)

Upvotes: 1

Dário
Dário

Reputation: 2082

I like both @Chris Lawlor's and @starkeen's answers and since OP asked about "40x" I'm going to suggest redirecting to a 404 error since it doesn't give away the fact the files exist.

This is what I'm currently using in one of my projects:

# Hide files not concerning the user
RedirectMatch 404 \.(htaccess|htpasswd|ini|log|sh|inc|bak|bkp|sql)$

Upvotes: 1

Amit Verma
Amit Verma

Reputation: 41219

You can also deny access to file extensions using RedirectMatch directive :

RedirectMatch 403 ^/.+\.(php|html|gif)$

This will return a 403 forbidden error for clients if they request any uri that ends with .php or .html or .gif . You can add more extensions to the pattern using a bar | .

Upvotes: 2

Michael Mrozek
Michael Mrozek

Reputation: 175375

<FilesMatch "\.ext$">
    Deny from all
</FilesMatch>

See the Apache documentation on FilesMatch and Deny

EDIT: Artefacto makes a good point, this will return 403, not 404, if that's important for your purposes

Upvotes: 5

Artefacto
Artefacto

Reputation: 97825

If you really want a 404 (and not a 403), you can use mod_rewrite:

RewriteEngine on
RewriteRule \.ext$ - [R=404]

Upvotes: 13

Chris Lawlor
Chris Lawlor

Reputation: 48902

<FilesMatch "\.(htaccess|htpasswd|ini|log|sh|inc|bak)$">
Order Allow,Deny
Deny from all
</FilesMatch>

Loaded with some common extensions, add more as you need.

Upvotes: 31

Related Questions