htaccess file tips and tricks
Htaccess (hypertext access) found as an .htaccess file is the default name of a directory and file level configuration file that allows for decentralized management of apache web server configuration. .htaccess file located inside the web tree, and is able to override a subset of the server’s global configuration.
htaccess file configuration is a very important basic knowledge every webmaster should be familiar with. htaccess file is a part of the website and the server security, it can prevent access of unwanted bots, htaccess used to create proper access to files and folders during the framework development. htaccess allows to create custom global error messages for your server and much more.
In order to view and modify so called “dotted” htaccess file you will need to edit it on host. Microsoft Windows doesn’t recognize dotted files like htaccess for some reason, in oreder to edit htaccess inside of your Microsoft Windows you will need to install special software. In linux .htaccess file edited with any available editor like vi from shell .
If you are editing .htaccess file inside your hosting cpanel it is highly important that your .htaccess file have the correct permissions set in order to prevent other people from modifying the file and taking control over your entire website. The permissions should be set at “644, rw-r-r”. With most FTP software, you can check the permissions by right clicking on the file and choosing “permissions” or “CHMOD”. You can do it from ssh or shell remotely with linux “chmod” command : sudo chmod 644 web/.htaccess
We created the list of useful basic commands you should know to modify your htaccess file.
Admin Email Address configuration with htaccess
You can define default admin email adress with ease using SetEnv command and placing following lines into your htaccess
SetEnv SERVER_ADMIN example@email.com
Allow / Disallow IP addresses
htaccess file makes it possible to define IP or IP range of impressions to your website, this practice is useful when you are modifying your website or you want to block bad bots or spammers traffic to your website. Maybe you have locally website with specified language and you don’t want to loose resourses on traffic from another languages .
The code below will ensure access from one IP only :
<Limit GET POST PUT>
order deny,allow
deny from all
allow from 12.342.62.890
</Limit>
You can set more then one IP to access your server :
<Limit GET POST PUT>
order deny,allow
deny from all
allow from 12.345.67.890
allow from 890.67.345.12
</Limit>
To protect your server or blog from unwanted ripping or spamming software access or unwanted bots access you can add following lines into your htaccess file for example if you want to protect blog from ripping software :
RewriteBase /
RewriteCond %{HTTP_USER_AGENT} ^Anarchie [OR]
RewriteCond %{HTTP_USER_AGENT} ^ASPSeek [OR]
RewriteCond %{HTTP_USER_AGENT} ^attach [OR]
RewriteCond %{HTTP_USER_AGENT} ^autoemailspider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Xenu [OR]
RewriteCond %{HTTP_USER_AGENT} ^Zeus.*Webster [OR]
RewriteCond %{HTTP_USER_AGENT} ^Zeus
RewriteRule ^.* - [F,L]
You can block access by referrer by adding following lines into your htaccess file botsite.com and othersite.com are unwanted refferers :
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} botsite\.com [NC,OR]
RewriteCond %{HTTP_REFERER} othersite\.com [NC,OR]
RewriteRule .* – [F]
</ifModule>
If you want to block one or more IP address, you can use following commands :
<Limit GET POST PUT>
order allow,deny
allow from all
deny from 12.345.67.890
</Limit>
Automatic CHMOD definitions
Chmod is a linux shell command used to specify file or folder permissions. We can use htaccess file to ensure that all the files and folders are with the properly permissions. This method is useful when we have lots of files and folders and we don’t want to spend our time to set permissions to each file and folder. In order to do it fast we will add following lines in our htaccess, example below will set chmod 644 to htaccess files, 755 to pl files, 755 to ini files and 644 to jpg files :
chmod .htaccess files 644
chmod pl files 755
chmod ini files 755
chmod jpg files 644
Cache filetypes with htaccess
You can significally increase your server load times by caching specified files with htaccess. There are lots of methods of caching and more advanced PHP, Python or another programming language caching methods where you can cache particular file types or conditions. We will show you the simple method of caching files with htaccess file :
To cache files you will need to define time in minutes , seconds , hours , years or months.
Following example will cache image files for 24 hours (86400 seconds) :
<FilesMatch “.(gif|jpg|jpeg|png|ico)$”>
Header set Cache-Control “max-age=86400?
</FilesMatch>
Or caching html files for 24 hours :
<FilesMatch “.(html|htm)$”>
Header set Cache-Control “max-age=86400?
</FilesMatch>
Here is the simple convertion of minutes hours and seconds : 24hr = 1440 minutes = 86400 seconds
Changing default page index.html or index.php
By default your server will redirect visitors to index page like index.php or index.html, you can declare commands to open another page instead :
DirectoryIndex notindex.html
Custom server error page with htaccess
Once you created your beautiful well designed website, you will probably want to create great looking error page. Sometimes server drops users to error page in cases page wasn’t found or there is lots of trafic to your page. You can call customly created html error page to show the errors to your visitors. Add CSS stylesheet to the html error page and it will get a great look. Here is htaccess definitionwhere error.html is your customly created html file for errors.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /error.html [L]
Html error page could be created for any server error occurence :
ErrorDocument 400 /error/400.html
ErrorDocument 401 /error/401.html
ErrorDocument 403 /error/403.html
ErrorDocument 404 /error/404.html
ErrorDocument 500 /error/500.html
Default language and timezone
Sometimes we need to tell our server and programming framework what language we are using as a default language, we can add code below into our htaccess file for USA English :
DefaultLanguage en-US
To set timezone we will use another great prectice, we will add default timezone into htaccess, once again we will use setenv command :
SetEnv TZ America/New_York
Deny access by time
Yes, apache is a smart piece of software, and if we are talking about time, you can deny access to the files and folders by tim, 13 | 14 | 15 are off times, and nobody can access to the website or directoy in 13,14 and 15 o’clock.
RewriteCond %{TIME_HOUR} ^(13|14|15)$
RewriteRule ^.*$ – [F,L]
Disable hotlinking
We created already tutorial on disable hotlinking and this tutorial is available here : disabling hotlinking with htaccess
Disable Script Execution
When we want just to store executable files like .php, html, pl or xml in our folder, we can prevent these files from being executed, htaccess allows you to do that with following code :
AddHandler cgi-script .php .pl .jsp .asp .sh .cgi
Options -ExecCGI
The code above will prevent execution of files with .php .pl .jsp .asp .sh .cgi extensions
Hide Server signature with htaccess
You can disable server signature output by adding code below :
ServerSignature Off
Disable file viewing
Access to any file could be disabled by another apache commands added to your htaccess file :
<files desticted.html>
order allow,deny
deny from all
</files>
In example above destricted.html is the file you want to prevent from viewing.
You can prevent many file types from being viewed on your server, and here is the rule for that :
<FilesMatch “\.(htaccess|htpasswd|ini|psd|eps|log|sh)$”>
Order Allow,Deny
Deny from all
</FilesMatch>
Files with htaccess|htpasswd|ini|psd|eps|log|sh extension will be prevented from viewing.
Note : It’s a good practice to prevent htaccess file only from viewing. So you are typing only .htaccess extension :
<Files .htaccess>
Order Allow,Deny
Deny from all
</FilesMatch>
Disable directories access
You have a bad code and unsecured website if your visitors can browse files and folders just like on their own PC, you can block access to any folder using htaccess, al the files will be executed from your server script only :
Disallow viewing open directories : “forbidden” error message will be shown to the visitor
Options All -Indexes
Command reversed by adding + synbol, it allows viewing open directories
Options All +Indexes
You can prevent access to the specified file extensions if you want to allow directory browsing :
IndexIgnore *.flv*.avi*.mov*
Disguise File Extensions
You will need to diguise file extensions sometimes for security or other reasons :
AddType application/x-httpd-php .html
AddType application/x-httpd-cgi .php
In the code above php files will be shown as html, and cgi files will be shown as php files.
Show the source code
You can show the source code of any file instead of executing it on server. You will need to create folder storing all source code files, create .htaccess file in this folder and enter following lines :
RemoveHandler cgi-script .pl .py .cgi .php .js
Now you can save any file you want to show the source code in that folder. Once user redirected to the file functions.pl for example located in that folder, he will see the source code of this file.
Force SSL with htaccess
You can forse SSL from your htaccess file and only https version of the page will be acceptable. This practice is useful if you have SSL certificate and your pages will be viewed from secure connections.
SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq “example.com”
ErrorDocument 403 https://example.com
You can use more simple version of commands if your mod_ssl disabled :
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
Force Subdomain with htaccess
If you want to show particular files of your website with subdomain, and you already installed subdomain, you can use this code to redirect your visitors to the subdomain instead of directory :
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^subdomain\.example\.com$ [NC]
RewriteRule ^/(.*)$ http://subdomain.example.com/$1 [L,R=301]
Force Download Filetypes
Sometimes we want to make sure that content is downloaded and not just viewed. Following code will force users to download the content of mentioned extensions like mov,avi,mpg,jpg,mp3 :
AddType application/octet-stream .mov
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .jpg
AddType application/octet-stream .mp3
Force www and without www
If we want constant domain name of our website for example to make domain.com www.domain.com we will use code below :
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.example.com$
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301]
And if we want to redirect users from www.domain.com to domain.com, we will use the same code without www :
RewriteEngine on
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.example\.come$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
Limiting upload size
We can tell our server to limit upload size via htaccess :
LimitRequestBody 10240000
Exaple above limits upload of 10MB (10240000 bytes) .
MIME Types definition
You can set or add MIME types inside of your htaccess file
AddType image/x-icon .ico
AddType application/x-shockwave-flash .swf
Password protection of files and folders
Tutorials are moved, you can view extended versions by clicking the links.
Tutorial on htaccess protected files and folders
You can generate your own htpasswd file dynamically using PHP
Redirect Entire Site
This tutorial might be helpful when you are moving domain name from one to another and want to redirect your traffic to another website or domain.
Change http://www.redirect-to.com to the domain name you want redirect to :
RewriteEngine On
RewriteRule ^(.*)$ http://www.redirect-to.com/$1 [R=301,L]
For permanent redirection, you can use code below :
Redirect permanent / http://www.domain.com/
If you want to redirect file with 301 redirect, use the commands :
redirect 301 /oldfiles/mypage.html http://www.example.com/newfiles/mypage.html
To redirect files from one directory to another use code below :
Redirect permanent /oldfiles/ http://www.example.com/newfiles/
Rename htaccess
In security reasons you may change htaccess name using the code below :
AccessFileName htacce.ss
Rewrite rule
To enable mod_rewrite you will need to enter following command in you htaccess, make sure it is not enabled already by your hosting company :
RewriteEngine on
