Secure your web applications through .htaccess file ~ Hybrid Mobile Apps Development, React Native, Flutter, JavaScript, Darts, iOS, Android, NodeJS
Coding Savvy FB Twitter Google
» »

Secure your web applications through .htaccess file

Hi everyone, For today and the coming days we are going to dwell more on security for web apps ,
Now we are going to learn how to improve security using the .htaccess file,This is a very important thing your web application must have to prevent attacks from malicious users, I will highly recommend that you use this practice for your existing and ongoing project to improve the security.
It is very simple to implement all we have to do is just create the .htaccess file and put it on our web server public directory.
As for those that are using CMS such as Joomla, Wordpress e.t.c your .htaccess is automatically edited by your CMS but you can also use this to add extra security measure, But please ensure that you understand this tutorial properly and you back up you previous .htaccess file.
Secure your wed application through .htaccess file

.htaccess file short for Hypertext Access, It is a configuration file used by Apache-based web servers that controls the directory that it "lives" in--as well as all the sub-directories underneath that directory.
.htaccess--it begins with a period, and ends with "htaccess." If you edit it, you need to make sure that it stays that way, and doesn't end up with a .txt or .html extension.
Not all web host allow you to edit your .htaccess but you can always create your own .htaccess file and upload it to your directory, it will control the access if the current directory and the sub directories under it.

What can I do with .htaccess file?

There are lot of things you can do with the file and I am going to make sure I discuss enough tips on configuring the file to the maximum security level.

Custom Error Pages

Costume error page are important It helps in showing your visitors a user friendly page to show that an error has occur through their requests or if it is from the server itself.
Costume error page also give your site a better SEO, Note that you are not allowed to put Google Adsense ads on your error pages. Firstly you will have to create and error file in any programming language you are using, In this case I will use .html file for explanation.
Once the HTML file has been created for my error pages. Error 404 is shown when the requested page dose not exist on the server, To create an error page for such situation we can create an HTML file and name it 404.html now we can create a folder in the public directory that is /error/ now let put our error file inside that directory so that we can link to it like this http://yourwebsite.com/error/404.html.
After this has been done you can specify the location of each error files in your .htaccess file like this.

ErrorDocument 401 /error/401.html
ErrorDocument 403 /error/403.html
ErrorDocument 404 /error/404.html
ErrorDocument 500 /error/500.html

Set Time Zone

Most of developers who host their server in abroad have issues with time zone because the server time will be set according to the country it is sited, Most developer overcome this using their sever side language but this will take time.
.htaccess File allows you to easily set your server time zone from it. By putting the environmental variable like below:
#set time zone
SetEnv TZ Africa/Lagos

Note that TZ in the code stands for TimeZone followed by the continent and the city. .

Directory Protection


Developer often forget that if an attacker know how your files are structured it give them more details on how to break through the security of your web application. This incredible feature of making the directories inaccessible by the public user will make is harder for anyone to know how your file and folders are been structured. To disable directory access add this code to your .htaccess file.
# disable directory browsing
Options All -Indexes

But if you want to enable directory access you can use this.
# enable directory browsing
Options All +Indexes

Remove www from site url

Sometime we like to remove www from website url to make it search engine friendly in case you have a long url.
In case you want your website to be shown as example.com instead of www.example.com, This can be archived through the .htaccess file.
but first we need to enable URL rewrite.
#remove www for SEO
Options +FollowSymLinks -MultiViews
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
You need to replace the example.com with your site URL

Compress text, html, javascript, css, xml e.t.c


We can use .htaccess file to compress some script file, This will increase the loading speed of the server.
To do that we can add this line to our file
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

Prevent bandwidth steeling from your website.


Some websites loose lot of bandwidth to another website because they have their pictures linked to from another website. This is a common practice by some other webmasters, We need to prevent this so that your server can maintain it bandwidth.
To archive this we need to add this line to the .htaccess file:
#stop people stealing bandwidth from your website by using images that are hosted in your web server
#RewriteBase /
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?kwarapolyweb.com/.*$ [NC]
RewriteRule .(gif|jpg|swf|flv|png)$ /feed/ [R=302,L]

Block attempt to process proc/self/environ.


We need to block an attempt to process this file, It how an attacker get more information from your server .
To do that we need ti stop it with this code
# proc/self/environ? no way!
RewriteCond %{QUERY_STRING} proc/self/environ [OR]

Block out any script or attack through URL


We need to do this, Just using your sever side code is not enough, Treating this request before it even gets to your web application is the best.
Add the following line to your .htaccess file to block out invalid request through URL. Lately we send all bocked request to the home page,In case you home page file is not index.php change the last line form index.php to whatever your homepage file name.

# Block out any script trying to set a mosConfig value through the URL
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]
# Block out any script trying to base64_encode crap to send via URL
RewriteCond %{QUERY_STRING} base64_encode.*(.*) [OR]
# Block out any script that includes a <script> tag in URL
RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL
RewriteCond %{QUERY_STRING} GLOBALS(=|[|\%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL
RewriteCond %{QUERY_STRING} _REQUEST(=|[|\%[0-9A-Z]{0,2})
# Send all blocked request to homepage with 403 Forbidden error!
RewriteRule ^(.*)$ index.php [F,L]

Secure the .htaccess File.


Since it is the .htaccess file that is handling the security of your web application, The first thing an attacker will try to do is to edit or delete the file. To prevent access to our .htaccess file we need to add the following line to the file itself.
# secure htaccess file
< files ".ht*">
deny from all
< /files >

OPTIONAL


Prevent Viewing a specific file This line can be used to prevent viewing of a file.
# prevent viewing of a specific file
 <files secretfile.jpg="" >
order allow,deny
deny from all
</files >

In this code above we are preventing access to the picture secretfile.jpg
Deny some file extension from running
If you want to prevent access to file with some extensions.
# multiple file types
<filesmatch fla="" htaccess="" htpasswd="" ini="" log="" php3="" phps="" psd="" sh="">
Order Allow,Deny
Deny from all
</filesmatch >

Search Engine friendly URL
To make your website URL more easy to get and to make it search engine friendly you can use this system.
#http://codingsavvy.com/file.php?owner=peters to http://codingsavvy.com/files/peters
RewriteRule ^files/([a-zA-Z0-9_-]+)$ files.php?owner=$1
RewriteRule ^files/([a-zA-Z0-9_-]+)/$ files.php?owner=$1

For multiple parameters.
# http://codingsavvy.com/blog.php?category=jquery&post=Getting_started_with_jquery to http://codingsavvy.com/blog/jquery/Getting_started_with_jquery RewriteRule ^blog/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ blog.php?category=$1&post=$2 RewriteRule ^blog/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/$ blog.php?category=$1&post=$2

# http://codingsavvy.com/message.php?username=peters&category=inbox&sort=date&pager=5 to http://codingsavvy.com/message/peters/inbox/date/5
RewriteRule ^message/([a-zA-Z0-9_-]+)/([a-zA-Z]+)/([0-9]+)/([0-9]+)$ message.php?username=$1&category=$2&sort=$3&page=$4
RewriteRule ^message/([a-zA-Z0-9_-]+)/([a-zA-Z]+)/([0-9]+)/([0-9]+)/$ message.php?username=$1&category=$2&sort=$3&page=$4
Secure directory by disabling script execution
# secure directory by disabling script execution
AddHandler cgi-script .php3 .phtml .pl .py .jsp .asp .htm .shtml .sh .cgi

Block visitors referred from indicated domains
# block visitors referred from indicated domains
RewriteCond %{HTTP_REFERER} unwanted.com [NC,OR]
RewriteCond %{HTTP_REFERER} badfriend.com [NC,OR]
RewriteRule .* - [F]

Options -ExecCGI

Block some unwanted bots from crawling your website
Hackers user robots to get private information about your website.

SetEnvIfNoCase ^User-Agent$ .*(craftbot|download|extract|stripper|sucker|ninja|clshttp|webspider|leacher|collector|grabber|webpictures) HTTP_SAFE_BADBOT
SetEnvIfNoCase ^User-Agent$ .*(libwww-perl|aesop_com_spiderman) HTTP_SAFE_BADBOT
Deny from env=HTTP_SAFE_BADBOT


Deceive Attackers by hiding the extension of your files
Sometime to be on the safe side you need to hide your file extension from the public.
Below They will see any file that is .php as .g file.
#let them see php as g
RewriteRule ^(.*)\.g$ $1.php

I case you don't want any extension to show ,To make http://codingsavvy.com/home.php as http://codingsavvy.com/home
RewriteRule ^([^/.]+)/?$ $1.php

Was this article helpful?
Thanks! Your feedback helps us improve tutorials.

You May Also Like...

2 comments:

  1. Oga , This is too complex ooo. Can't do this myself. Will mess things up.

    ReplyDelete
    Replies
    1. Please paste your blog URL and a shot of your former htaccess file maybe I can help.

      Delete