Tuesday, September 3, 2013

Top 10 HTACCESS Scripts

For those of you getting into the “nuts and bolts” of website design, you will find that there are times where you will need to create and/or modify the .htaccess file. In this regard, I have provided some of the most important .htaccess scripts I have come across, many which I use and have found indispensable.
If you are unfamiliar with .htaccess creation, all you need is “notepad” (not msword) since you want to ensure that there is no default character formatting. You add the code you wish into it, and then upload the file titled .htaccess to your public folder where the html files are stored (typically called public_html, or www, etc). In some cases there will be unique .htaccess files for the different folders, especially useful if you wish to block access to some folders and their files, but not all. Ok, that being said, here they are,

1. Mobile Detetction & Redirection Script
MobRedirect is a mobile detection & redirection tool kit to provide complete solutions for mobile device detection and redirection. MobRedirect supports all types mobile devices. MobRedirect is helpful to detect and redirect mobile users to mobile site. MobRedirect is a .htaccess script. It is very powerful and Robust script than any other php detection and redirection script. Sometimes in some cases PHP detection and redirection script won’t detect mobile device, but this is not happened in .htaccess script.

2. Custom Error Page
By default your browser will serve up an error page in those cases where a page link is broken, or someone manually enters a link to a page that does not exist. The best solution is to create a custom page since this will allow you to track errors (if you wish), and you now have the opportunity to brand the page creatively, have it match your existing website, … and what most will do is provide a site-map, search engine, etc. to help someone find content on your site that you know does exist. You could create the page as a .html, but if you wish to track which pages are not being found (though Google Webmaster tools will do this for you as well), all you do is create an normal html page, and then save it as a .php page and add a bit of code into it.
< ?php
$ip = getenv (“REMOTE_ADDR”);
$requri = getenv (“REQUEST_URI”);
$servname = getenv (“SERVER_NAME”);
$combine = $ip . ” tried to load ” . $servname . $requri ;
$httpref = getenv (“HTTP_REFERER”);
$httpagent = getenv (“HTTP_USER_AGENT”);
$today = date(“D M j Y g:i:s a T”);
$message = “$today \n
$combine  \n
User Agent = $httpagent \n
$note \n
$httpref “;
$message2 = “$today \n
$combine \n
User Agent = $httpagent \n
$note \n
$httpref “;
$to = “name@youremail.com”;
$subject = “Email Title of Error Page”;
$from = “From: name@youremail.com\r\n”;
mail($to, $subject, $message2, $from);
echo $message;
As you can see in the code above, it will send you an email when a page is not found (nice to find broken links on your site), and it will tell you the server name, IP address, referer, date it was accessed, page name of error, etc. I have noted that most of my page errors come from bots that have stored previous versions of site pages that have had the names changed, and hackers who are trying to break into directories (more on this next).
Here is an example of the email notice I received when a bot tried to access a page that no longer exists: tried to load www.patillab.com/zencart/index.php?main_page=contact_us
User Agent = Mozilla/5.0 (compatible; Ezooms/1.0; ezooms.bot@gmail.com)
Ok, so now for the .htaccess file, you add “ErrorDocument 404 /404NameOfPage.php” to the file. “404″ is the name of the error handling, so it is a good idea to keep this in the file name for the sake of recognition. The actual code I use for my page is: ErrorDocument 404 /404NotFound.php

3. Selective Access Blocking

Ok, so I noted above that hackers will spend their nights trying to break into your directories. Mine are very secure, but just the same I will block an IP address of one that is seeking to access my configuration files. In this case you simply add the following to the .htaccess file.
order allow,deny
deny from
deny from
allow from all
As you can see, this is very simple. You have “order allow,deny” followed by the “deny from … with the IP address of the miscreants. Then you finish with “all from all”.

4. Force a Trailing Slash on URL

Some feel that it is best to always have a trailing slash on the primary URL since this encourages the search engines to explore deeper. It may, not sure. If this is important to you, yes, there is an .htaccess code snippet for this:
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

5. Disable Hotlinking
Websites which have a gallery of images will often find their bandwith slowing down as a result of hotlinking. Hotlinking occurs when someone links directly to an image on your site, instead of a remote image on their own local server. The .htaccess code to prevent this is:
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]#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>

6. HTACCESS Fast Caching

For websites that have lots of images, video, and flash, it is a good idea to speed up your site’s page load by caching images and other memory intensive files. This code will override one’s own cache settings, … the only potential downside is if you change your content often a visitor may not see your new content until they refresh the page a couple of times though as you can see, the cache time varies by type of file, so it should meet the needs of most.
#1 year
Header set Cache-Control “max-age=29030400, public”
# 1 WEEK
Header set Cache-Control “max-age=604800, public”
# 2 DAYS
Header set Cache-Control “max-age=172800, proxy-revalidate”
# 1 MIN
Header set Cache-Control “max-age=60, private, proxy-revalidate”

7. Stop Spammers on WordPress

For those of you who have blogs, yet don’t use askimet (I don’t since only the non-commercial version is free), here is some code that will help keep the spam to a minimum. What it does is prevent spam bots directly access to your wp-comments-post.php file (used to post comments on your blog). Of course some will simply visit your blog site and manually spam, … yeah!
RewriteEngine On
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.*yourdomainname.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]

8. Logging PHP Errors

It is a good idea to hide PHP errors from visitors since hackers will often use the errors to perform a process of elimination when trying to access a vulnerability in dynamic php pages. this code will do that.
# display no errors 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

9. Wp-config Added Protection

The wp-config file is the WordPress configuration file that links up to the server. As a general rule you will make the file non-writeable through CHMOD settings after installation (and delete the install directory which writes to this file), but it is also a good idea to secure it even more by adding the following code into your .htaccess file.
order allow,deny deny from all

10. Disable Directory Browsing

I often come across websites where the directory is accessible. This allows me to open up every folder, and browse for whatever I want. An easy way to prevent this is to the add the following to your .htaccess file.
# disable directory browsing Options All -Indexes
Well, that’s it for this one, will add more as time allows!