Theme Forest - Download 1000's of Themes

15+ Useful .htaccess Code Snippets to Optimize your Website

by | Programming, Resources | (0) Comments | 2,026 views

Apache .htaccess file is at the heart of your web server and control how your website will react to different actions performed by your visitors.

Here is a great list of code snippets and scripts for .htaccess file to optimize your website in many ways like redirection, performance, ease of use, security and more! All of the snippets needs to be pasted into your .htaccess file, which is located on the root of your Apache server.

You might also want to check:

List of .htaccess code snippets

Speed up your site with .htaccess caching

awesome ways to implement caching on your website using Apache .htaccess (httpd.conf) files on the Apache Web Server. These methods are extremely simple to set up and will dramatically speed up your site!

# 1 YEAR
<FilesMatch "\.(ico|pdf|flv)$">
Header set Cache-Control "max-age=29030400, public"
</FilesMatch>
# 1 WEEK
<FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
# 2 DAYS
<FilesMatch "\.(xml|txt|css|js)$">
Header set Cache-Control "max-age=172800, proxy-revalidate"
</FilesMatch>
# 1 MIN
<FilesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=60, private, proxy-revalidate"
</FilesMatch>

Source: http://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching.html

Stop spam on your WordPress blog

Sick of spammers on your WordPress blog? Of course, Akismet helps a lot, but your .htaccess file can also help: Today’s recipe is a snippet that prevent spam bots to directly access your wp-comments-post.php file, which is used to post comments on your blog.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.*yourdomainname.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]
</IfModule>

Source: http://www.wprecipes.com/reduce-spam-on-your-wordpress-blog-by-using-htaccess

Prevent hotlinking

Hotlinking is the use of an image from one site into a web page belonging to another site. Many bloggers are hotlinked, and have their bandwidth used on another websites. Here’s a solution to protect your WordPress blog from hotlinking.

RewriteEngine On
#Replace ?mysite\.com/ with your blog url
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mysite\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
#Replace /images/nohotlink.jpg with your "don't hotlink" image url
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]

Source: http://www.wprecipes.com/how-to-protect-your-wordpress-blog-from-hotlinking

Force trailing slash

Some search engines remove the trailing slash from urls that look like directories – e.g. Yahoo does it. But – it could result into duplicated content problems when the same page content is accessible under different urls.

The solution was to create a .htaccess rewrite rule that adds the trailing slashes to these urls.

<IfModule mod_rewrite.c>
 RewriteCond %{REQUEST_URI} /+[^\.]+$
 RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
</IfModule>

Source: http://perishablepress.com/code-snippets/

Force download of a specific filetype

When offering some files such as mp3s, eps or xls, for download on your site, you may force download instead of letting the browser decide what to do. This snippet will force the download of .xls and .eps files from your server.

<Files *.xls>
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</Files>
<Files *.eps>
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</Files>

Source: http://snipplr.com/view.php?codeview&id=54752

Cross Domain Font embedding for Firefox

This rule allows you to embed fonts cross domain. Especially good when you are serving your fonts from a CDN.

<FilesMatch "\.(ttf|otf|eot|woff)$">
<IfModule mod_headers.c>    
    Header set Access-Control-Allow-Origin "http://yourdomain.com"
</IfModule>
</FilesMatch>

Source: http://snipplr.com/view/53703

Redirect mobile devices

The following set of rewrite rules will redirect all popular mobile devices to a specific mobile directory on your website.

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/m/.*$
RewriteCond %{HTTP_ACCEPT} "text/vnd.wap.wml|application/vnd.wap.xhtml+xml" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT}  "maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "wapp|wapr|webc|winw|winw|xda|xda-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "up.browser|up.link|windowssce|iemobile|mini|mmp" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "symbian|midp|wap|phone|pocket|mobile|pda|psp" [NC]
#------------- The line below excludes the iPad
RewriteCond %{HTTP_USER_AGENT} !^.*iPad.*$ 
#-------------
RewriteCond %{HTTP_USER_AGENT} !macintosh [NC] #*SEE NOTE BELOW
RewriteRule ^(.*)$ /m/ [L,R=302]

Source: http://snipplr.com/view.php?codeview&id=55114

Redirect different feeds to a single format

WordPress provides feeds in four different formats: Atom, RDF, RSS, and RSS2. These days, most people are only using the RSS2 format. So what about redirect Atom, RDF, RSS to RSS2?

Open your .htaccess file (located at the root of your WordPress install) and add the following code. Don’t forget to modify http://example.com/feed/ by your feed url, and backup your .htaccess file before editing it!

<IfModule mod_alias.c>
 RedirectMatch 301 /feed/(atom|rdf|rss|rss2)/?$ http://example.com/feed/
 RedirectMatch 301 /comments/feed/(atom|rdf|rss|rss2)/?$ http://example.com/comments/feed/
</IfModule>

Source: http://www.wprecipes.com/redirect-feeds-to-a-single-format

Configure your website for HTML5 videos

This snippet will help you to configure your server properly to work with the latest HTML5 video standards.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
AddType video/ogg .ogv
AddType video/ogg .ogg
AddType video/mp4 .mp4
AddType video/webm .webm
AddType application/x-shockwave-flash swf

Source: http://snipplr.com/view.php?codeview&id=53437

Log PHP errors

Log errors to a file, and prevent showing them to the user. Make sure that the file exists and youre able to write to it.

# display no errs to user
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
# log to file
php_flag log_errors on
php_value error_log /location/to/php_error.log

Source: http://css-tricks.com/snippets/htaccess/php-error-logging/

Run PHP inside JavaScript files

Solution for this is to make your server parse all files ending in .js. Just create a .htaccess if it doesn’t exist in the directory in which you wish to include and run PHP code inside all .js files. Add these lines at the end of .htaccess:

AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js

<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>

Source: http://www.kavoir.com/2010/07/how-to-execute-run-php-code-inside-javascript-files.html

Protect WordPress Blog From Script Injections

 

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})
RewriteRule ^(.*)$ index.php [F,L]

Source: http://www.wprecipes.com/how-to-protect-your-wordpress-blog-from-hotlinking

Protect the .htaccess file itself

$1You must secure your .htaccess before you think about using the same to re-model your WordPress setup. The below piece of code will secure your .htaccess from any kind of external access. Also, it takes care of the case sensitive characters in the file name. So, .hTACcesS will also be secured just fine.$1

<Files ~ "^.*\.([Hh][Tt][Aa])">
 order allow,deny
 deny from all
 satisfy all
</Files>

Source: http://www.onextrapixel.com/2011/11/03/unleashing-htaccess-for-wordpress/

Protect your WordPress blog from hotlinking

Hotlinking is the use of an image from one site into a web page belonging to another site. Many bloggers are hotlinked, and have their bandwidth used on another websites. Here’s a solution to protect your WordPress blog from hotlinking.

RewriteEngine On
#Replace ?mysite\.com/ with your blog url
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mysite\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
#Replace /images/nohotlink.jpg with your "don't hotlink" image url
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]

Source: http://www.wprecipes.com/how-to-protect-your-wordpress-blog-from-hotlinking

Only your IP accesses wp-admin Folder

wp-admin folder is the core of WordPress and if a hacker gets access to this then your life might just come to an end. In such cases it is suggested to give access to your IP address only for the wp-admin folder. You will have to place your root’s .htaccess file inside the wp-admin folder with the below piece of code appended to it. This will make sure that the changes are applied only inside wp-config directory. Use the below code to get this rolling:

<LIMIT GET>
order allow, deny
deny from all
allow from xx.xx.xx.xx
</LIMIT>

Source: http://www.onextrapixel.com/2011/11/03/unleashing-htaccess-for-wordpress/

Use Browser Caching to Improve Blog Speed

A WordPress blog might get a beating from every corner if it loads slowly. This is when the below code comes in handy. It will add cache control headers to your blog which will increase the caching timespan on browsers. This will of course decrease your blog’s load time. The code should be self-explanatory.

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
</IfModule>

Source: http://www.onextrapixel.com/2011/11/03/unleashing-htaccess-for-wordpress/

Removing /category/ from Permalinks

Let us remove /category/ from the category based permalinks in WordPress. Paste the below code into your .htaccess file just above the first RewriteRule in the default part of .htaccess code that is used by WordPress. Just for your reference (and to clear any confusion), after you paste the code then this is how the final default code will look like:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^category/(.+)$ http://mydomain.com/Removing /category/ from Permalinks [R=301,L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Source: http://www.onextrapixel.com/2011/11/03/unleashing-htaccess-for-wordpress/