Saturday, December 21, 2024

.htaccess Tricks To Speed Up Your Website

Is your unoptimized website bleeding money due to a slow average page load time? This guide will show you how to optimize your .htaccess (apache) file to implement speed improvements.

Just a one second delay in page response can result in a 7% reduction in conversions, and 40% of users abandon shopping carts that takes more than 3 seconds to load, according to KissMetrics. With more users making purchase decisions on mobile devices each year, page load optimization won’t patiently wait on your back burner any longer without affecting your bottom line.

Fortunately, there are several effective tactics to speed up your website without even touching your main website code. Even if you have little experience with .htaccess or server modification, this detailed guide will give you the tools and knowledge to take a bite out of your page load.

What is .htaccess?

Glad you asked. An .htaccess file allows you to modify Apache web server configuration settings without modifying the main configuration file – in other words, you can customize the way the server behaves while keeping the core settings intact, much like using a child theme in WordPress. Most webhosts allow clients to use .htaccess files, but if you’re not sure, check with your host.

How Do You Use .htaccess?
Simply open any text editor and create a new file called .htaccess. Could it really be that simple? Well, yes and no. Most likely, your computer will perceive the .htaccess file as an operating-system file and hide it from view. To see the file, you’ll need to follow a guide like this one from SitePoint to show hidden files. Once you have that taken care of, you’re ready to move on!

Some considerations before you start:
When editing .htaccess files, minor mistakes in syntax can break your site. Therefore, it’s always a good idea to back up any existing .htaccess files (if applicable) before you begin editing. If necessary, you can comment out an existing line by using the # symbol at the beginning.

Some of the common ways an .htaccess file can get broken:

  • Bad syntax – in other words, improperly formatting the code.
  • If you make .htaccess edits through cPanel, they can conflict with changes you made by hand.

With the proper precautions and a reliable source to copy and paste code from, there’s no reason not to take advantage of .htaccess to improve your site.

7 Tricks for Improving Site Speed with .htaccess

On to the good part: how can we harness the power of .htaccess to improve page load time? Try one (or all!) of these 7 tried-and-true customizations:

Turn on content caching
Google recommends caching all static (permanent) resources – including Javascript, CSS, media files, images, and more. Caching saves these resources to the user’s local memory so files don’t need to be downloaded for repeat visits. This modification alone can significantly reduce page load time – not to mention bandwidth usage.

While some servers will cache a few static resources by default, it’s best to explicitly tell your server to cache all of them. More importantly, the default expiration period for cached entities is one hour, while Google recommends a minimum of one month, and even up to one year (but no more than that).

To ensure the server is caching all static resources and for the maximum time recommended by Google, we’ll be using mod_expires. Open .htaccess and paste the following inside:


# Set up caching on static resources for 1 year based on Google recommendations
<IfModule mod_expires.c>
ExpiresActive On
<FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav|js|css|gif|jpg|jpeg|png|swf)$">
ExpiresDefault A29030400
</FilesMatch>
</IfModule>

You see whether it’s working by viewing the headers for a file on your server. Using Chrome, open the developer tool and go to the Network tab. Reload your page and click on a css file. Make sure you see the expires date in the response headers:

Compress output with gzip
This .htaccess modification compresses the size of the resources as they’re being downloaded to the user’s browser, thereby increasing page load. By default, it won’t compress anything below 500 bytes — which is a good thing, because compression below that size can ironically increase load time.

To utilize this mod, copy and paste the code below into your .htaccess file:


# Enable gzip compression
<ifModule mod_gzip.c>
 mod_gzip_on Yes
 mod_gzip_dechunk Yes
 mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$
 mod_gzip_item_include handler ^cgi-script$
 mod_gzip_item_include mime ^text/.*
 mod_gzip_item_include mime ^application/x-javascript.*
 mod_gzip_item_exclude mime ^image/.*
 mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

Turn off directory indexing
This mod hits two birds with one stone, improving speed and privacy.

By default, any visitor can actually look inside any directory that doesn’t have an index file (index.html, index.php, etc.) in it. That means configuration files and other sensitive data could potentially be up for grabs to malicious users.

Unless you want to add a blank index.html file to every folder on your website (and trust future developers to do the same), take the easy road and modify your .htaccess file instead. In the process, you’ll be saving a bit of server resources – especially if you have very large directories. To turn off directory indexing, open your .htaccess file and add:


#Disable Directory Indexes
Options -Indexes

Prevent hotlinking
Have you ever had the option to display an image from another website via URL? That’s called hotlinking, and it actually eats up bandwidth on the host’s server. Thankfully, it’s possible to prevent other domains from hotlinking to your website. To ensure nobody is using your precious bandwidth, add this script to your .htaccess file:


#Prevent Hot Linking
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

Force files to download instead of open in browser
If your site serves a lot of media files, speed is a top priority. If it’s practical for your users to download files to their hard drives once rather than stream repeatedly from your website, this mod will save your bandwidth:


#Force certain types of files to download instead of load in browser
#Only include filetypes that you want to download automatically
AddType application/octet-stream .csv
AddType application/octet-stream .xls
AddType application/octet-stream .doc
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf

Deny bad bots
Your public website is constantly being crawled and scraped by bots. Some of these bots are essential – they index your site so it will show in search results. However, there are plenty of bots that aren’t so friendly. Spam bots and scrapers might be bogging down your server, using up bandwidth and resources.. We can block bots based on the user-agent they provide.

The script below denies some bad bots, but isn’t exhaustive. Look to AskApache for resources to help identify more bad bots to block, and use our script as a template if you prefer to add more:


#Block Bad Bots
RewriteCond %{HTTP_USER_AGENT} ^WebBandit [OR]
RewriteCond %{HTTP_USER_AGENT} ^2icommerce [OR]
RewriteCond %{HTTP_USER_AGENT} ^Accoona [OR]
RewriteCond %{HTTP_USER_AGENT} ^ActiveTouristBot [OR]
RewriteCond %{HTTP_USER_AGENT} ^addressendeutshland
RewriteRule ^.* - [F,L]

You can test to see that it’s working by changing your user-agent in Google Chrome. In the developer tools, go to Settings->Overrides->Useragent. Setting your Useragent to one of the blocked bots, then visit your site. You should get a 403 denied error.

Deny malicious IPs
Nothing slows down a site quite like a server attack. If you know the IP address of a user who is trying to break into or abuse your website, you can deny a specific IP, IP blocks, or domains with .htaccess:


#Deny Malicious IPs
order allow,deny

#deny single IP
deny from 1.1.1.1

#deny IP block
deny from 1.1.1.

allow from all

Putting It All Together

Eager to use every tool possible to speed up your site in .htaccess? We put everything together for you here:


<IfModule mod_rewrite.c>
RewriteEngine On

#Prevent Hot Linking
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

#Block Bad Bots – This is a small list. You can add bots to it.
RewriteCond %{HTTP_USER_AGENT} ^WebBandit [OR]
RewriteCond %{HTTP_USER_AGENT} ^2icommerce [OR]
RewriteCond %{HTTP_USER_AGENT} ^Accoona [OR]
RewriteCond %{HTTP_USER_AGENT} ^ActiveTouristBot [OR]
RewriteCond %{HTTP_USER_AGENT} ^addressendeutshland
RewriteRule ^.* – [F,L]
</IfModule>

# Set up caching on static resources for 1 year based on Google recommendations
<IfModule mod_expires.c>
ExpiresActive On
<FilesMatch “\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav|js|css|gif|jpg|jpeg|png|swf)$”>
ExpiresDefault A29030400
</FilesMatch>
</IfModule>

# Enable gzip compression
<ifModule mod_gzip.c>
 mod_gzip_on Yes
 mod_gzip_dechunk Yes
 mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$
 mod_gzip_item_include handler ^cgi-script$
 mod_gzip_item_include mime ^text/.*
 mod_gzip_item_include mime ^application/x-javascript.*
 mod_gzip_item_exclude mime ^image/.*
 mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

#Disable Directory Indexes
Options -Indexes

#Force certain types of files to download instead of load in browser
AddType application/octet-stream .csv
AddType application/octet-stream .xls
AddType application/octet-stream .doc
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf

#Ban Malicious IPs
order allow,deny
deny from 1.1.1.1
allow from all

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay Connected

942FansLike
1,002FollowersFollow
355FollowersFollow

Latest Articles

programmer hi tech