How to Block a Certain File Type with .htaccess

Blocking a certain file type can be useful. For example, if you’ve migrated from an oldschool website consisting of tons of .htm files. Your new website may be delivering a custom 404 page for files that do not exist, but the only one requesting your ancient site are robots.

In that case, it doesn’t make sense to deliver your 404 from your fancy new website. Building the 404 page is resource intensive and processes tons of PHP to let a robot know – this file does not exist. You’d rather want the server to say – Access Denied with the intention of making the robot stop the habit of hitting your server for files that do not exist.

This can easily be done in .htaccess. Instead of rendering a full web page, you can tell the webserver to return a 403 the moment it requests any .htm file.

In Apache 2.4 the syntax would be like this:

RewriteEngine On
RewriteBase /
# Block access to .htm files and deliver 403 access denied
RewriteCond %{REQUEST_URI} \.htm$
RewriteRule ^(.*)$ - [F,L]

You can mix the core lines into, for example, a WordPress .htaccess. Just make sure to inject the two crucial lines after RewriteEngine On and your RewriteBase line.

Happy blocking!