Articles Web Development

Useful .htaccess Snippets Collection. 15 Tricks to Take Better Control of Your Site

htaccess-snippets
5/5 (1)

Web performance and loading speed are among the hottest topics in the web. If your site or blog is slow, chances are people won’t ever come back. The good news is that some of the most important site optimizations can be achieved by means of .htaccess tricks. In this blog post we provide a useful .htaccess snippets collection with the help of which you’ll be able to redirect URLs, prevent hotlinking, enhance site speed, among many other things.

.htaccess is a special configuration file that provides multiple commands for controlling and configuring the Apache Web Server. However, by no means all web developers know and understand it fully. The true power of .htaccess snippets often goes unnoticed. These can be utilized not only for speeding up your site, but also for SEO optimization and a number of other purposes.

Make a Backup First

Before you apply any changes, it’s advised to make a copy of the current .htaccess file since only one character in the wrong place can make the code incorrect. As a result, your whole website will go down. So, having a backup file stored in a safe place on your computer, hard drive or cloud storage guarantees you will always have a working version of .htaccess.

Each time you update the .htaccess file on your server, make sure your website properly runs. Otherwise, revert back to the saved copy of .htaccess file and upload it on top of the version with errors.

15 .htaccess Snippets to Make Your Site Much More Useful

SEO-friendly URLs

Websites with clear URL structure rank higher than those with addresses like ‘index.php?product_id=’. Ideally, a SEO-friendly URL should feature a keyword and duplicate some content from your blog post title or the name of the page, which guarantees it will be properly indexed by Google or other search engines.

1
2
3
<Files magic>
	ForceType application/x-httpd-php5
</Files>

Redirect form your old domain to the new one

The technique is better known as 301 redirect. With its help you can redirect both separate pages and the entire sites. To redirect a single page, use code:

1
Redirect 301 /oldpage.html http://www.yoursite.com/newpage.html

For the entire site:

1
Redirect 301 / http://newsite.com/

In both cases, the old URL comes first, with the address of the new domain following it in the second part of code.

Remove www from URL

For the users’ convenience or for better SEO ranking, you might want to remove www from the URL of your site. With the help of the following code you’ll be able to remove www and forward the users to your site address starting with http:/ ….

1
2
3
RewriteEngine On
RewriteCond %{HTTP_HOST} !^mysite.com$ [NC]
RewriteRule ^(.*)$ http://mysite.com/$1 [L,R=301]

Error Pages

None of your visitors should see a blank page when they end up on a broken URL. Instead, create a beautifully-designed and informative error page that would provide the visitors with working links to keep on browsing your site.

1
2
3
4
5
ErrorDocument 400 /errors/badrequest.html
ErrorDocument 401 /errors/authrequest.html
ErrorDocument 403 /errors/forbidden.html
ErrorDocument 404 /errors/notfound.html
ErrorDocument 500 /errors/servererror.html

Better site speed with better caching

The faster your page loads, the higher your site will rank in search results. Web developers make a struggle to create websites that would smoothly run on both desktop and mobile devices, and not make them wait for long till the site loads. That’s when caching comes in handy. However, at this point there is one important thing to consider – you should make sure there are no other caching systems in place. Additionally, you need to decide on caching length. In the example below you can see how to set files to cache for 24 hours.

1
2
3
<FilesMatch ".(flv|gif|jpg|jpeg|png|ico|swf|js|css|pdf)$">
	Header set Cache-Control "max-age=28800"
</FilesMatch>

Prevent files from caching

If you don’t want particular files to cache, you can easily control it by adding a certain code to the .htaccess file. Here is how to disable caching for the particular files:

1
2
3
<FilesMatch ".(pl|php|cgi|spl|scgi|fcgi)$">
Header unset Cache-Control
</FilesMatch>

Site on maintenance note

I guess each of us has once come across Apple’s popular “Coming Soon” maintenance page that appears when they take their store down, before a new product launch. You can follow this example and introduce our visitors to such a page before some big announcements. With the help of the following code you can redirect everyone except yours’ IP address and 127.0.0.1 that stands for a special “home” IP address.

1
2
3
RewriteCond %{REMOTE_ADDR}  !your_ip_address
RewriteCond %{REMOTE_ADDR}  !127.0.0.1
RewriteRule !offline.php$ http://www.example.com/back_soon.html [L,R=307]

Use the vary header to crawl mobile content

Many web developers give the same URL for both mobile and desktop versions of their websites. Instead of opting for the responsive design, these make alter the HTML. In such cases, the “Vary” header is an indispensable component to make Google know that the HTML changes for mobile web users, which provides for better page indexing.

1
Header append Vary: User-Agent

Prevent image hotlinking

As so often happens, someone steels images from your website without your permission. That’s what people call image hotlinking. By steeling images from your site, people also take advantage of your bandwidths. For this not to happen, add the following code into your .htaccess.

1
2
3
4
5
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourwebsite.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourwebsite.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ http://i.imgur.com/g7ptdBB.png [NC,R,L]

rel=”canonical” tag

In case you have several pages with similar content or you want prevent search engines from indexing other websites that have copied your content, you can make user of rel=”canonical” tag to make Google know that your page is the original one. Also, the same tag can be applied to images and PDF files. Here is how the latter works.

1
2
3
4
5
6
7
<Files download.pdf>
Header add Link '<http://www.tomanthony.co.uk/httest/pdf-download.html>; rel="canonical"'
</Files>
 
<Files product.jpg>
Header add Link '<http://www.tomanthony.co.uk/httest/product-page.html>; rel="canonical"'
</Files>

Block access to backup and source files

Some file may go under risk and pose a great security danger when someone has access to them. For it not to happen, apply the following code.

1
2
3
4
5
6
7
8
9
10
 
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
    ## Apache 2.2
    Order allow,deny
    Deny from all
    Satisfy All
 
    ## Apache 2.4
    # Require all denied
</FilesMatch>

Password protect a directory

Protecting documents, images and other data from unauthorized users is of high value. Of course, you can accomplish this by means of PHP to ask users for login authorization information, however the same can be done much easier and effectively with .htaccess. You will need to prepare two files – the first one is the .htaccess file with code and another one is .htpasswd file with usernames and passwords off all the allowed users. Here is how the .htaccess file looks like.

1
2
3
4
5
 
AuthType Basic
AuthName "restricted area"
AuthUserFile /home/davidwalsh/html/protect-me-dir/.htpasswd
require valid-user

Force files to download

When you provide some content on your website, you can share a link for the users to open a document, audio or video file, etc. in a new window or download it to their desktops. To achieve the latter, add the following code to the .htaccess file and your visitors will be provided with a copy of the content you’ve share onsite.

1
2
3
4
<Files *.md>
    ForceType application/octet-stream
    Header set Content-Disposition attachment
</Files>

Gzip compression

Compression of HTML and CSS files is quite popular now as it provides for faster page loading. If for some reason you still don’t compress files on your site, it’s high time to start practicing it. Add this code to the .htaccess file on your server.

1
2
3
4
5
6
7
8
9
10
<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>

Ban someone from your site

If you don’t want particular users or some malicious parties to have access to your site content, then you can easily ban them from your website with the help of the following code:

1
2
3
4
5
6
<Limit GET POST>
order allow,deny
deny from 123.456.78.9
deny from 987.654.32.1
allow from all
</Limit>

As you see, some tricks on this list are more familiar to the wide audience than others, like 301 redirect that pro SEOs make use of, error pages, etc. Having quick access to the basic .htaccess snippets will not only save tons of your time an deffort to decide on how to optimize your web resource, but also make it much more functional and user-friendly. So, don’t forget to bookmark this post and share some cool tips with your friends after you’ve read this.

Leave a Reply

Your email address will not be published. Required fields are marked *