WP-Mix

A fresh mix of code snippets and tutorials

Whitelist File Names via Apache/.htaccess

I’ve posted tons of tutorials showing how to block things with Apache/.htaccess. Generally blocking involves defining a list and then forbidding access to it. In this quick post, we’re going to change it up, by defining a list and forbidding access to anything that is not included. The list can be anything, IP addresses, request URIs, referrer information, user agent, or anything at all.

For this example, we have a list of file types that are allowed public access. All other file types are not allowed. Here is the magic code:

# whitelist file types
<IfModule mod_rewrite.c>
	RewriteCond %{REQUEST_FILENAME} -f
	RewriteCond %{REQUEST_FILENAME} !\.(php|xml|css|js|json|gif|jpg|jpeg|jpe|png|svg|ico|mpg|mpeg|mp4|pdf|txt|eot|otf|ttf|woff2)$ [NC]
	RewriteRule (.*) - [F,L]
</IfModule>

That code can be added to your site’s public root .htaccess file, or added directly to Apache configuration file. The choice is yours.

Let’s go thru the code to get a better idea of how it works:

  1. First line is a comment, ignored by Apache
  2. Second line opens the mod_rewrite container
  3. Third line checks if the requested file name
  4. Fourth line checks if the file exists
  5. Fifth line defines our list of allowed file types
  6. Sixth line closes the mod_rewrite container

So in plain speak, the code does the following for each URI request:

Check if the file exists and is on the “always allowed” list. If so, continue as usual. Otherwise for any requested file that does not exist and is not on the list, deny access by returning a 403 Forbidden error.

Of course, the list of file names is just one example. You can modify the code above to whitelist just about anything. Have fun :)

Learn more

.htaccess made easy