Hosting & Servers

Essential .htaccess rules for every site

Implement smart redirects, Gzip compression, browser caching, and protection of sensitive files on your website with practical htaccess rules. Complete guide with real-world examples.

Hosting & Servers

Introduction: Why htaccess is a Vital Tool for Every Site Administrator?

The .htaccess file is one of the most powerful directory-level server management tools used on Apache web servers. Using this simple text file, you can change server behavior without needing access to Apache's main configuration files. From 301 redirects to file compression, browser caching, and protecting sensitive files—all of this can be done with just a few lines of code in htaccess. In this article, we will explore practical and useful rules that every site administrator should know. If you use shared hosting or a virtual server, Apache is likely your primary web server, and these rules will be effective for you. ServerNet also supports Apache in its hosting services, but this article focuses on general techniques that are provider-independent.

Smart Redirects with htaccess

Redirects are one of the most common uses of htaccess. Whether you want to move an old page to a new one, change a domain, or direct users from HTTP to HTTPS, .htaccess is the best option.

Permanent 301 Redirect

A 301 redirect tells search engines that the page has moved permanently. This is essential for preserving SEO ranking and preventing 404 errors. Simple example:

Redirect 301 /old-page.html https://example.com/new-page.html

If you need to redirect an entire directory:

RedirectMatch 301 /old-directory/(.*) https://example.com/new-directory/$1

Here, $1 preserves part of the original URL and transfers it to the destination.

Redirect from HTTP to HTTPS

For better security and SEO, all users should be directed to the HTTPS version of the site. Place the following code in the root .htaccess file:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

This code first checks if HTTPS is not active, then redirects the request to the secure version.

Redirect www Domain to non-www (or Vice Versa)

For domain consistency, choose one version. Example for redirecting www to non-www:

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

And for the reverse (non-www to www):

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Common mistake: Forgetting RewriteEngine On at the beginning of RewriteRule codes. Without this line, none of the rewrite rules will work.

Gzip Compression to Increase Loading Speed

Compressing HTML, CSS, JavaScript, and even font files before sending them to the browser reduces transfer size by up to 70%. This directly impacts site speed and user experience.

Enabling Gzip with htaccess

Add the following code to your .htaccess file:

<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript application/json application/xml
  AddOutputFilterByType DEFLATE image/svg+xml font/ttf font/otf font/woff font/woff2
</IfModule>

This code tells the server to compress the specified file types using the Deflate algorithm. The mod_deflate module is usually active on Apache hosts.

Testing Compression

To ensure compression is active, you can use online tools like checkgzipcompression.com or the curl command in the terminal:

curl -H "Accept-Encoding: gzip" -I https://example.com

If you see the Content-Encoding: gzip header in the response, compression is active.

Troubleshooting tip: If compression is not working, make sure the mod_deflate module is enabled on the server. On some shared hosts, you may need to request this from support.

Browser Caching with htaccess

Browser caching allows users to store static files (images, CSS, JS) in local memory so they don't need to be re-downloaded on subsequent visits. This significantly increases loading speed.

Setting Cache-Control Headers

Add the following code to .htaccess:

<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/jpg "access plus 1 year"
  ExpiresByType image/jpeg "access plus 1 year"
  ExpiresByType image/gif "access plus 1 year"
  ExpiresByType image/png "access plus 1 year"
  ExpiresByType image/webp "access plus 1 year"
  ExpiresByType text/css "access plus 1 month"
  ExpiresByType application/javascript "access plus 1 month"
  ExpiresByType text/javascript "access plus 1 month"
  ExpiresByType application/x-javascript "access plus 1 month"
  ExpiresByType image/x-icon "access plus 1 year"
  ExpiresByType font/ttf "access plus 1 year"
  ExpiresByType font/otf "access plus 1 year"
  ExpiresByType font/woff "access plus 1 year"
  ExpiresByType font/woff2 "access plus 1 year"
</IfModule>

These settings tell the browser to cache images for one year and CSS/JS files for one month. You can adjust the numbers based on your needs.

Using Cache-Control Instead of Expires

A more modern method is to use the Cache-Control header:

<IfModule mod_headers.c>
  <FilesMatch "\.(ico|jpg|jpeg|png|gif|webp|svg|woff|woff2|ttf|eot)$">
    Header set Cache-Control "max-age=31536000, public"
  </FilesMatch>
  <FilesMatch "\.(css|js)$">
    Header set Cache-Control "max-age=2592000, public"
  </FilesMatch>
</IfModule>

Here, max-age is in seconds: 31536000 seconds equals one year, and 2592000 seconds equals one month.

Common mistake: Setting too long a cache duration for files that change frequently (like main CSS files). If you change a CSS file and the user has an old cache, the site may display incorrectly. Solution: use versioning in file names (e.g., style.v2.css) or set a shorter duration for dynamic files.

Protecting Sensitive Files with htaccess

Important files like wp-config.php in WordPress, .env in Laravel, or database configuration files should not be directly viewable in the browser. htaccess provides simple tools for this.

Blocking Access to Specific Files

To prevent access to sensitive files, use the following code:

<FilesMatch "\.(env|config|sql|log|bak|old|inc)$">
  Order allow,deny
  Deny from all
</FilesMatch>

This code blocks access to files with the specified extensions for all users. You can add more extensions.

Protecting Sensitive Directories

For directories like /includes or /uploads that should not be listed directly:

Options -Indexes

This simple line prevents the directory file list from being displayed. If a user accesses a directory without an index file, they will receive a 403 Forbidden error instead of a file list.

Blocking Specific IPs

If you want to block access from a specific IP:

Order Allow,Deny
Allow from all
Deny from 192.168.1.100
Deny from 10.0.0.0/8

Here, 192.168.1.100 is a specific IP and 10.0.0.0/8 is an IP range.

Password Protection (Basic Authentication)

To protect a specific directory with a password:

  1. Create a .htpasswd file outside the public directory (e.g., in /home/user/.htpasswd).
  2. Add a username and password using the htpasswd command: htpasswd -c /home/user/.htpasswd admin
  3. In the .htaccess file of the target directory, add the following code:
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /home/user/.htpasswd
Require valid-user

This method is very useful for admin sections or staging sites.

Important security note: Never place the .htpasswd file in a public directory (like public_html). Otherwise, users could download the password file by guessing the path.

Advanced Settings: Blocking Hotlinking and Malicious Bots

Hotlinking occurs when other sites use your images without permission, consuming your bandwidth. With htaccess, you can block this.

Preventing Image Hotlinking

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

In this code, replace example.com with your domain. This rule returns a 403 Forbidden error to browsers that link to your images from other domains.

Blocking Bad Bots

Some bots (like scrapers) consume server resources. You can block them by User-Agent:

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (ahrefsbot|mj12bot|semrushbot) [NC]
RewriteRule .* - [F,L]

This code blocks Ahrefs, Majestic, and Semrush bots. You can expand the list with other bot names.

Conclusion

The .htaccess file is a powerful and flexible tool that can improve your site's performance, security, and speed with just a few lines of code. From smart redirects to compression and browser caching, all these settings can be implemented without changing the main site code. Always remember to back up the original .htaccess file before applying changes. If you use shared hosting and encounter a 500 Internal Server Error, simply restore the file via FTP. By practicing and using the examples in this article, you can gain more control over your server and provide a better experience for your users.

ServerNet Support

ServerNet engineering & editorial team — specialists in infrastructure, networking and web hosting.

Contact
Share:

Comments 0

No comments yet — be the first!

Leave a comment