MIME Types and Content Handling in .htaccess Files

Managing MIME types and content handling in .htaccess files is crucial for ensuring that web content is delivered correctly and securely. MIME types inform the browser about the type of content being served, allowing it to handle the content appropriately.

Setting MIME Types

You can define custom MIME types in your .htaccess file to ensure that files are processed correctly by the browser.


AddType application/pdf .pdf
AddType application/x-shockwave-flash .swf
AddType text/html .html

In this example:

Enforcing Character Encoding

To specify the character encoding for your files, use the AddDefaultCharset directive.


AddDefaultCharset UTF-8

This directive ensures that all text files are served with UTF-8 encoding, which is widely used and supports a broad range of characters.

Preventing MIME Type Sniffing

MIME type sniffing can be a security risk as it allows browsers to infer the content type of files. To prevent this, you can set the X-Content-Type-Options header to nosniff.


<IfModule mod_headers.c>
    Header set X-Content-Type-Options nosniff

This header instructs browsers not to try to guess the MIME type, ensuring they rely on the provided Content-Type header.

Handling Content-Disposition

The Content-Disposition header controls how content is presented (inline or as an attachment).


<FilesMatch "\.(pdf|zip)$">
    Header set Content-Disposition attachment

This example sets the Content-Disposition to attachment for PDF and ZIP files, prompting the browser to download these files rather than displaying them inline.

Gzip Compression

Gzip compression reduces the size of files sent to the client, speeding up load times.


<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript

This directive compresses various text-based file types, improving overall performance.


Configuring MIME types and content handling in .htaccess files is essential for ensuring that content is delivered correctly and securely. By setting appropriate MIME types, enforcing character encoding, preventing MIME type sniffing, controlling content disposition, and enabling Gzip compression, you can significantly enhance the performance and security of your web applications. Regularly review and update your .htaccess configurations to keep up with best practices and emerging standards.