Home > seo > htaccess

.htaccess file 40 useful tricks and tips for Websites {practical guide}

Ask a Question

Introduction to .htaccess file

Hey there! If you’re a website owner or a webmaster, there’s a powerful tool you absolutely need to know about – the .htaccess file. It’s like a secret key that can unlock the full potential of your website. Trust me; understanding .htaccess will make a huge difference in how you manage your website and can have a profound impact on security, SEO, and performance.

The .htaccess file is a powerful configuration file used by web servers, such as Apache, to control website behaviour. With the right knowledge and techniques, you can utilize the .htaccess file to enhance your website’s functionality, security, and performance. Here are 40 tips and tricks to help you make the most out of .htaccess:

1. How to Enable GZIP Compression?

GZIP compression reduces file sizes, leading to faster page load times. Add the following code to your .htaccess file:



  AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/x-javascript

2. How to Set Expires Headers?

By setting expiration headers, you can instruct browsers to cache certain files. This reduces server requests and improves page load speed. Add the following code:



  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 text/css "access plus 1 month"

  ExpiresByType application/javascript "access plus 1 month"

3. How to Redirect www to Non-www or Vice Versa?

To redirect visitors from www to non-www or vice versa, use the following code:

3.1 Redirect www to non-www

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]

RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

3.2 Redirect non-www to www

RewriteEngine On

RewriteCond %{HTTP_HOST} ^example\.com [NC]

RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

4. How to Block IP Addresses?

If you want to block specific IP addresses or a range of IP addresses, use the following code:

Order Deny,Allow

Deny from 123.45.67.89

You can replace `123.45.67.89` with the IP address you want to block.

5. How to Enable Directory Listing?

To prevent directory listing on your website, add the following line to your .htaccess file:

Options -Indexes

 6. How to Customize Error Pages?

Create custom error pages to provide a better user experience. For example, to create a custom 404 error page, add the following code:

ErrorDocument 404 /404.html

Replace `/404.html` with the URL of your custom error page.

7. How to Force HTTPS?

Ensure secure connections by redirecting HTTP to HTTPS using the following code:

RewriteEngine On

RewriteCond %{HTTPS} off

RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

8. How to Set the Default Page for your website?

Specify the default page for your website using the following code:

DirectoryIndex index.html index.php

This tells the server to look for “index.html” or “index.php” as the default page.

9. How to Password Protect a Directory?

To password-protect a directory, use the following code:

AuthType Basic

AuthName "Restricted Area"

AuthUserFile /path/to/.htpasswd

Require valid-user

Replace `/path/to/.htpasswd` with the path to your .htpasswd file.

10. How to Prevent Hotlinking?

Hotlinking refers to using images or files hosted on your website on another website. Prevent hotlinking using the following code:

RewriteEngine On

RewriteCond %{HTTP_REFERER} !^$

RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?example.com [NC]

RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

Replace `example.com` with your own domain.

Apologies for the confusion. Here are the remaining tips and tricks to complete the list of 40 useful .htaccess tricks and tips for websites:

11. How to Enable Browser Caching?

To enable browser caching for certain file types, add the following code:



  ExpiresActive On

  ExpiresByType text/html "access plus 1 week"

  ExpiresByType image/jpg "access plus 1 month"

  ExpiresByType image/jpeg "access plus 1 month"

  ExpiresByType image/gif "access plus 1 month"

  ExpiresByType image/png "access plus 1 month"

  ExpiresByType text/css "access plus 1 month"

  ExpiresByType application/javascript "access plus 1 month"

12. How to Enable Server Side Includes (SSI)?

To enable Server Side Includes, which allows you to include external files in your web pages, use the following code:

AddType text/html .shtml

AddOutputFilter INCLUDES .shtml

13. How to Block Bad Bots from crawling your site?

Protect your website from malicious bots and crawlers using the following code:

SetEnvIfNoCase User-Agent "BadBot" bad_bot

Deny from env=bad_bot

14. How to Redirect a Specific File or Directory?

To redirect a specific file or directory to another location, use the following code:

Redirect 301 /old-file.html http://example.com/new-file.html

Redirect 301 /old-directory http://example.com/new-directory

15. How to Limit File Upload Size?

Restrict the maximum file upload size on your website using the following code:

LimitRequestBody 1048576

This example sets the limit to 1MB. Adjust the value as needed.

16. How to Set PHP Configuration Options?

You can set various PHP configuration options directly in the .htaccess file. For example, to increase the maximum upload file size in PHP, use the following code:

php_value upload_max_filesize 20M

php_value post_max_size 20M

17. How to Disable Directory Browsing?

Prevent directory browsing on your website with the following code:

Options -Indexes

18. How to Prevent Image Hotlinking from Specific Domains?

To prevent the hotlinking of images from specific domains, add the following code:

RewriteEngine On

RewriteCond %{HTTP_REFERER} ^http(s)?://(www\.)?example.com [NC,OR]

RewriteCond %{HTTP_REFERER} ^http(s)?://(www\.)?example2.com [NC]

RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

Replace `example.com` and `example2.com` with the domains you want to allow.

19. Set Default Charset

Specify the default character set for your website using the following code:

AddDefaultCharset UTF-8

20. Redirect HTTP to HTTPS for a Specific Page

To redirect a specific page from HTTP to HTTPS, use the following code:

RewriteEngine On

RewriteCond %{HTTPS} off

RewriteCond %{REQUEST_URI} ^/specific-page\.html [NC]

RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Replace `/specific-page\.html` with the URL of the page you want to redirect.

These additional tips and tricks will help you further optimize and secure your website using the .htaccess file. Remember to test your changes and refer to trusted sources for additional guidance.

Certainly! Here are more tips and tricks to complete the list of 40 useful .htaccess tricks and tips for websites:

21. How to Set Custom MIME Types?

Specify custom MIME types for specific file extensions using the following code:

AddType application/vnd.ms-fontobject .eot

AddType application/x-font-ttf .ttf

AddType application/x-font-opentype .otf

AddType application/x-font-woff .woff

22. How to Remove File Extensions from URLs?

To remove the file extension from URLs and make them more user-friendly, use the following code:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME}.html -f

RewriteRule ^([^\.]+)/$ $1.html [NC,L]

This example removes the `.html` extension.

23. How to Limit Access to .htaccess File?

Protect the .htaccess file itself by limiting access to it. Add the following code:

 

24. How to Redirect to a Maintenance Page?

If you need to put your website under maintenance, redirect all traffic to a maintenance page using the following code:

RewriteEngine On

RewriteCond %{REMOTE_ADDR} !^123\.45\.67\.89$

RewriteCond %{REQUEST_URI} !/maintenance.html$ [NC]

RewriteRule ^(.*)$ /maintenance.html [R=302,L]

Replace `123\.45\.67\.89` with your IP address and `/maintenance.html` with the path to your maintenance page.

25. How to Enable CORS Headers?

Allow cross-origin resource sharing (CORS) by adding the following code:



  Header set Access-Control-Allow-Origin "*"

26. How to Set Custom Error Documents?

Create custom error pages for various HTTP error codes using the following code:

ErrorDocument 400 /errors/400.html

ErrorDocument 403 /errors/403.html

ErrorDocument 404 /errors/404.html

Replace `/errors/400.html`, `/errors/403.html`, and `/errors/404.html` with the paths to your custom error pages.

27. How to Restrict Access Based on User Agent?

Limit access to your website based on user agents (browsers) using the following code:

RewriteEngine On

RewriteCond %{HTTP_USER_AGENT} ^.*(BadBot).*$ [NC]

RewriteRule ^.*$ - [F,L]

Replace `(BadBot)` with the user agent you want to block.

28. How to Disable Server Signature?

Prevent the server signature from being displayed in HTTP response headers with the following code:

ServerSignature Off

29. How to Enable HTTPS for a Specific Directory?

Force HTTPS for a specific directory on your website using the following code:

RewriteEngine On

RewriteCond %{HTTPS} off

RewriteRule ^specific-directory/ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Replace `specific-directory` with the directory you want to secure.

30. How to Redirect to a Mobile Version of the Site?

Redirect mobile users to a separate mobile version of your website with the following code:

RewriteEngine On

RewriteCond %{HTTP_USER_AGENT} "android|blackberry|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]

RewriteRule ^(.*)$ http://m.example.com/$1 [L,R=302]

Replace `http://m.example.com` with the URL of your mobile site.

31. How to Enable Secure HTTP Headers?

Enhance the security of your website by enabling secure HTTP headers. Add the following code:



    Header always set X-Content-Type-Options "nosniff"

    Header always set X-XSS-Protection "1; mode=block"

    Header always set X-Frame-Options "SAMEORIGIN"

    Header always set Content-Security-Policy "default-src 'self';"

32. How to Force File Download?

Force a file to be downloaded rather than displayed in the browser using the following code:



    Header set Content-Disposition attachment

This example forces PDF and ZIP files to be downloaded.

33. How to Rewrite URLs for SEO-friendly URLs?

Rewrite URLs to create SEO-friendly URLs using the following code:

RewriteEngine On

RewriteRule ^category/([a-zA-Z0-9-]+)/?$ category.php?name=$1 [L]

This example rewrites URLs from `category.php?name=category-name` to `category/category-name`.

34. How to Redirect to a Maintenance Page with HTTP Status Code?

Redirect all traffic to a maintenance page with the appropriate HTTP status code using the following code:

RewriteEngine On

RewriteCond %{REQUEST_URI} !/maintenance.html$ [NC]

RewriteRule ^(.*)$ /maintenance.html [R=503,L]

Replace `/maintenance.html` with the path to your maintenance page.

 35. How to Deny Access to Specific File Types?

Prevent access to specific file types using the following code:



    Order allow,deny

    Deny from all

This example denies access to SQL, log, and XML files.

36. How to Redirect HTTP to HTTPS for Entire Site?

Force all traffic to use HTTPS for the entire website using the following code:

RewriteEngine On

RewriteCond %{HTTPS} off

RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

37.How to Prevent Image Hotlinking with a Placeholder Image?

Prevent hotlinking of images and replace them with a placeholder image using the following code:

RewriteEngine On

RewriteCond %{HTTP_REFERER} !^$

RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?example.com [NC]

RewriteRule \.(jpg|jpeg|png|gif)$ /images/placeholder.jpg [NC,R,L]

Replace `example.com` with your own domain and `/images/placeholder.jpg` with the path to your placeholder image.

38. How to Limit Access by IP Address?

Restrict access to your website by allowing only specific IP addresses using the following code:

Order Deny,Allow

Deny from all

Allow from 123.45.67.89

Replace `123.45.67.89` with the IP address you want to allow.

39. How to Customize Directory Index Page

Customize the directory index page (e.g., when no specific file is requested) using the following code:

DirectoryIndex custom.html

Replace `custom.html` with the filename of your custom index page.

40. How to Redirect URLs with Query Parameters?

Redirect URLs with query parameters to a clean URL structure using the following code:

RewriteEngine On

RewriteCond %{QUERY_STRING} ^id=123$

RewriteRule ^product\.php$ /product-name? [R=301,L]

This example redirects `product.php?id=123` to `/product-name`.

These additional tips and tricks provide further options to optimize and secure your website using the .htaccess file. Remember to test your changes and refer to trusted sources for additional guidance.

Summary:

Discover the incredible power of .htaccess files! With .htaccess, you can enhance website security, optimize SEO, and boost performance. It’s a crucial tool for website owners and webmasters, offering endless possibilities to customize your website’s behaviour and interactions. Don’t miss out on the opportunities it brings!