How to deny/allow access to files using .htaccess file

Question:

How can I allow and deny HTTP access to files based on file extension? I need to deny access to all TXT files.

Answer:

Below you can find a simple examples on how to regulate download access to files using .htaccess file. In the first example the following .htaccess code will block access to all files with file extension .txt to all requests resulting in HTTP ERROR 403: Forbidden..

<FilesMatch ".txt">
    Order Allow,Deny
    Deny from All
</FilesMatch>

If an download access is required based on the source IP address it is possible to allow access per IP address basis. The following code will deny access to all and then allow access to .txt file to requests coming from eg. IP address 204.215.85.145:

<FilesMatch ".txt">
    Order Deny,Allow
    Deny from All
    Allow from 204.215.85.145/32
</FilesMatch>