Performance Optimization with .htaccess

Optimizing web performance is crucial for improving user experience and reducing server load. Apache’s .htaccess files offer a variety of tools to enhance performance. Here are some key techniques:

1. Enable Compression

Compressing files reduces their size, speeding up download times.

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

2. Leverage Browser Caching

Specify caching rules to store static resources locally.

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType text/javascript "access plus 1 month"
</IfModule>

3. Gzip Compression

Ensure Gzip compression is enabled for additional file types.

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript application/xml application/xml+rss
    AddOutputFilterByType DEFLATE application/vnd.ms-fontobject font/ttf font/opentype
</IfModule>

4. Avoid Image Hotlinking

Prevent other sites from using your images, saving bandwidth.

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F]

5. Enable Keep-Alive

Keep connections open to reduce latency for subsequent requests.

<IfModule mod_headers.c>
    Header set Connection keep-alive
</IfModule>

6. Optimize File Delivery

Set rules for optimized file delivery and HTTP/2 support.

<IfModule mod_headers.c>
    Header unset ETag
    FileETag None
</IfModule>

Conclusion

Using .htaccess files for performance optimization can significantly enhance website speed and efficiency. Implement these techniques to improve load times, reduce server load, and deliver a smoother user experience. Regularly review and update your .htaccess rules to adapt to evolving performance best practices.

Comments