How to Enable .htaccess file on Apache Server and Enable Gzip Compression

Page content

Enable .htaccess file on Apache Server

The .htaccess file is a crucial file on Apache server that can have a significant impact on website performance. Any error in this file can cause the site to stop functioning. It is why one should save a copy of the .htaccess file before making any changes to it.

.htaccess is useful in several regards including increased Wordpress security, speed optimization and even for preventing directory listing. When you install the Apache server, you first need to enable the .htaccess file so you can use it on your website.

In this tutorial, we will show you how to enable the .htaccess file on Apache server and use it to enable compression, browser caching and preventing directory listing. The .htaccess file can also be used to set redirects from one url to another and to deny or allow particular IPs. if you do not enable the .htaccess file, you might be forced to make the changes inside the Vhosts or Apache configuration file each time. To avoid that you can set a .htaccess file for each of the websites hosted on the server.

While there are several configuration changes that you can make inside the .htaccess file to speed up and secure your website, it is only possible on Apache server. Nginx server does not support .htaccess file.

Install Apache Server (Ubuntu 22.04)

Apache server can be easily installed on Ubuntu 22.04 with a few commands.

sudo apt update
sudo apt install apache2

Once the server installation is complete, you will need to allow Apache through the firewall.

sudo ufw app list

It will produce a list of available application profiles. If you are going to install ssl on your website, you can allow ‘Apache Full’ through the firewall and otherwise only ‘Apache’.

sudo ufw allow ‘Apache Full’

Once done, you can check the status of your Apache server and if it is running.

sudo systemctl status apache2

If the output shows Apache as active and running then fine, otherwise you can start the Apache server with the following command:

sudo systemctl start apache2

To stop the Apache server, run the following command:

sudo systemctl stop apache2

Now that you have the APache server installed and running, it is time to create a vhosts file for your new website. BY default the Apache server has one severe block enabled which has its root folder as /var/www/html. If you are planning to host only one site, you can make changes to the default vhosts file. However, if you plan to host more than one site on the same server, you must create separate root directories for each one of them.

sudo mkdir /var/www/mydomain

Now, we need to change ownership of the directory we have just created and change the permissions to allow the owner to read, write and execute files while allowing groups and others to only read and execute.

sudo chown -R $USER:$USER /var/www/mydomain
sudo chmod -R 755 /var/www/mydomain

Create a Vhosts file and enable .htaccess

We have created the root directory and assigned its ownership to the current user as well as changed permissions. Add a simple index.html file to the root folder. If you are planning to install Wordpress, you can now install it inside the new root directory.

Create a new Vhosts file with the following command.

sudo nano /etc/apache2/sites-available/mydomain.conf

Now, paste the following into that file.

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/mydomain
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

To enable the use of .htaccess file on the Apache server, we need to add one more piece of code inside the virtual hosts file.

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/mydomain
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

<Directory /var/www/mydomain>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

</VirtualHost>

Now, you can create a .htaccess file inside your root folder and use it. To create a .htaccess file in the root folder

sudo nano /var/www/mydomain/.htaccess

How to Enable GZIP Compression with .htaccess file

Enabling compression on your Wordpress website is very important. It speeds up your site by compressing content and also helps you rank higher since site speed is a critical ranking factor now.

Since Gzip is based on a lossless algorithm, the original data remains unchanged before and after compression. It can significantly enhance website performance. Gzip compression can significantly reduce the size of files by 80% or more which helps improve website speed and reduces bandwidth consumption. Once you have enabled Gzip on Apache server, you will see a significant difference in page loading times.

There are two ways to enable Gzip compression on Apache server. The first method is via the use of a plugin. Most cache plugins include the compression feature. However, they too write the code to the .htaccess file to enable Gzip compression. Otherwise, you can simply add the code that enables Gzip compression inside the .htaccess file. However, you will need to make sure that module deflate is enabled on the server. If not, you can enable it.

sudo a2enmod deflate

This will enable mod_deflate on the Apache server. You must restart the Apache server after enabling the module.

sudo systemctl restart apache2

If mod_deflate is already enabled on your server, you will receive a message that the module is already enabled.

 sudo a2enmod deflate
Considering dependency filter for deflate:
Module filter already enabled
Module deflate already enabled

Now, open the .htaccess file.

sudo nano /var/www/mydomain/.htaccess

And add the following piece of code to enable Gzip compression.


<IfModule mod_deflate.c>
# Compress HTML, CSS, JavaScript, Text, XML, and fonts
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml
</IfModule>

Once you have added the code to the .htaccess file, you can save it and close it using ctrl + S and ctrl + X. You can check if Gzip is enabled on your website using online tools like Giftofspeed.

How to Enable Browser caching in .htaccess

Enabling browser caching is a good method to ensure that your site loads faster. Browser caching improves page load times, reduces the pressure on the server and can lower bounce rates. Caching means storing temporarily. When a visitor visits your website, the browser can cache some of the website content so that it does not have to fetch the content for subsequent visits. If you do not enable browser caching, each request will be fully loaded from the origin server which will increase bandwidth consumption and hurt server performance.

You can also enable browser caching on your website by using a caching plugin also. For example, if you are using the W3TC plugin on your website, you can easily enable it by ticking a box.

However, it is generally better to enable browser caching through the .htaccess file since it gives you better control of the type of content you want to cache and the period for which browsers should store cache. All the website content does not get cached and it is mainly the static content which does not change too often is cached by browsers.

To enable browser caching, you need to have mod_expires enabled on your server. SSH to your server and:

sudo a2enmod expires

This will enable mod_expires and you can now restart the apache server. If you already have mod_expires enabled, you will receive a confirmation message that it is already enabled.

Once done, open the .htaccess file and add the following piece of code. Wordpress adds some of its own code to .htaccess. Make sure you do not disturb that piece of code. Insert any code either before Begin Wordpress or after End Wordpress. To ensure that nothing breaks when you are making changes to your .htaccess file, you can save a copy before applying changes.

Now, apply this piece of code inside the .htaccess file and you are done.

# BEGIN Expire headers  
<IfModule mod_expires.c>  
  # Turn on the module.
  ExpiresActive on
  # Set the default expiry times.
  ExpiresDefault "access plus 2 days"
  ExpiresByType image/jpg "access plus 1 month"
  ExpiresByType image/svg+xml "access 1 month"
  ExpiresByType image/gif "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType text/css "access plus 1 month"
  ExpiresByType text/javascript "access plus 1 month"
  ExpiresByType application/javascript "access plus 1 month"
  ExpiresByType application/x-shockwave-flash "access plus 1 month"
  ExpiresByType image/ico "access plus 1 month"
  ExpiresByType image/x-icon "access plus 1 month"
  ExpiresByType text/html "access plus 600 seconds"
</IfModule>  
# END Expire headers

So, this is how you can use the .htaccess file to speed up your blog/website. Wordpress users need to use these optimizations to ensure that their website loads faster.