How to setup caching & GZIP compression in Apache Web Server with .htaccess

To setup caching and GZIP compression in Apache Web Server with .htaccess, follow these steps:

  1. Enable mod_deflate: First, you need to enable the mod_deflate module in your Apache web server. You can do this by adding the following line to your Apache configuration file (httpd.conf):
LoadModule deflate_module modules/mod_deflate.so
  1. Create .htaccess file: Next, create a new file named .htaccess in the root directory of your website.
  2. Enable GZIP compression: Add the following lines to your .htaccess file to enable GZIP compression:
# Enable GZIP compression
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>
  1. hese lines will tell Apache to compress the specified file types before sending them to the user’s browser.
  2. Set caching rules: Add the following lines to your .htaccess file to set caching rules:
# Set caching rules
<IfModule mod_headers.c>
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=86400, public"
</FilesMatch>
</IfModule>
  1. These lines will set caching rules for the specified file types. The “max-age” value tells the browser to cache the files for a certain amount of time (in seconds).
  2. Save the .htaccess file: Save the changes to your .htaccess file and upload it to the root directory of your website.
  3. Test your website: Test your website using Google PageSpeed Insights or other similar tools to verify that GZIP compression and caching are working properly.

Note: These steps assume that you have access to the Apache configuration file and the ability to enable modules. If you are on a shared hosting plan, you may not have access to these settings and will need to contact your hosting provider for assistance.