Basics of .htaccess (Manage Redirects, Gzip Compression, and Caching)

The Apache .htaccess is a configuration file that is used to control the behavior of a website without changing the server's main settings. Discover how this file can be used for different purposes, like creating custom error pages, enabling response headers for caching, managing redirects, and password protection.

Basics of .htaccess

What is an .htaccess File?

An .htaccess (Hypertext Access) file is a configuration file that is used in Apache server-based shared web hosting environments. It is used to modify different server configurations like directory access, redirects, error pages, caching, and compression without affecting the server's core configuration. This file is usually placed in the root directory, but it can also be added to subdirectories to define certain rules for those directories.

 

How to Create an .htaccess File?

Creating this file does not require any special program and can be created with a simple text editor. However, there is one thing to remember, that this file has no name, and it should be saved with only the extension ".htaccess". When saving the file, choose "All Files" in the file type box and the file name must be only ".htaccess".

 

Redirect HTTP to HTTPS with .htaccess

This directive automatically redirects all visitors accessing the website over the HTTP protocol to the HTTPS version of the website. HTTPS protocol prevents sensitive information from being exposed by ensuring the connection between a client and server is secure. This directive requires the mod_rewrite module to be enabled, and it can be used like this: 

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
 

Custom Error Pages with .htaccess

This directive allows websites to redirect users to custom error pages instead of the server's default error pages. For example, if a user tries to visit a page that does not exist, it will lead to a 404 error. So we can show a custom 404 page with .htaccess using this directive and tell the server to display /404.html whenever a user tries to access a URL that does not exist.

ErrorDocument 404 /404.html

Common Error Codes:

CodeDescription
400Bad Request
401Unauthorized
403Forbidden Access
404Not Found
500Internal Server Error
502Bad Gateway
504Gateway Timeout
 

Custom Redirection with .htaccess

It is another useful directive that enables redirecting a user from one page to another. This directive can also have a redirect code like 301 for a permanent redirect or 302 for a temporary redirect. It is used as in the snippet below:

Redirect 301 /OldDir/OldFile.html /NewDir/NewFile.html

Password Protection with .htaccess

This directive makes it possible to protect web pages with a password. Whenever a user tries to access a protected area of the website, they will be asked to enter a username and password. To implement this restriction, we first generate htpasswd file that contains all the allowed usernames with their passwords. The content of this file will look like in the snippet below:

admin:123456
user:123123

After creating .htpasswd, we need to add authentication directives to our .htaccess file. Remember, this password protection will apply to the directory that contains the ".htaccess" file and all subdirectories.

AuthUserFile /absolute/pathto/.htpasswd
AuthType Basic
AuthName "Authorization Required"
require valid-user
 

Block IP Address with .htaccess

This is another useful feature that allows websites to restrict website access by blocking a user's IP address. However, it requires that Apache's AllowOverride must be configured to use relevant directives. For example, if we wanted to block the IP address "199.155.88.25", we would use the directives as in the following snippet:

order allow,deny
deny from 199.155.88.25 
allow from all
 

Restrict Direct Access to Files with .htaccess

We can restrict direct access to a single or multiple files like config.php, database.php, and .env or other sensitive files. When this directive is applied and a user tries to directly access the restricted file(s), Apache will return a 403 error. This restriction does not prevent the PHP application from using these files, and it can be implemented as in the snippet below:

# Deny access to a single file
<Files .env>
Order Allow,Deny
Deny From All
</Files>

# Deny access to multiple files
<FilesMatch "\.env|\.sql">
Order Allow,Deny
Deny From All
</FilesMatch>
 

Enable Gzip Compression with .htaccess

Gzip compression is a method used to reduce the size of files sent to the user's browser. It helps to load a website faster by reducing the amount of data transferred to the client's browser. We can enable this feature at a directory level or for certain MIME types as in the example below:

# Enables compression for documents where htaccess is placed 
<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
</IfModule>

# Enables compression by MIME type for plain text files, html, css, javascript and xml files
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/xml
</IfModule>
 

Enable Cache and Expire Headers with .htaccess

The two HTTP response headers (Cache-Control and Expires) can contribute to page speed optimization. The Cache-Control header uses the mod_headers module and tells the browsers and caches how the resources should be stored and reused. The Expires header uses the mod_expires module and tells the browsers for how long the response should be used from cache. The following is an example of how both response headers can be used:

# Cache headers for 45 days for allowed extensions
<ifModule mod_headers.c>
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=3888000, s-max-age=3888000, public"
</FilesMatch>
</ifModule>

# Expire headers for given file types for 45 days
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType text/plain "access plus 45 days"
ExpiresByType text/html "access plus 45 days"
ExpiresByType text/css "access plus 45 days"
ExpiresByType image/gif "access plus 45 days"
ExpiresByType image/png "access plus 45 days"
ExpiresByType image/jpeg "access plus 45 days"
ExpiresByType application/x-javascript "access plus 45 days"
ExpiresByType application/javascript "access plus 45 days"
ExpiresByType application/x-icon "access plus 45 days"
</IfModule>

NOTE: Different directives may require different Apache modules to work. Any misconfiguration or incorrect rules can cause a website to return a 500 Internal Server Error.