Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Use .htaccess File Effectively ?

DZone's Guide to

How to Use .htaccess File Effectively ?

· DevOps Zone
Free Resource

The DevOps Zone is brought to you in partnership with Sonatype Nexus. The Nexus Suite helps scale your DevOps delivery with continuous component intelligence integrated into development tools, including Eclipse, IntelliJ, Jenkins, Bamboo, SonarQube and more. Schedule a demo today

.htaccess file is the configuration file for the web servers running the Apache Web Server. It is very useful for configuring and redirecting Apache Web Server file system. 

Keep in mind that .htaccess file will be in hidden format. No one can see it directly by URL.

There are many uses of .htaccess files. Here, I will discuss about creating it and uses of it. 

Creating .htaccess file :

Open any text editor and save the file with name .htaccess. Enable mod_rewrite extension in php.ini file in Apache Web Server Configurations.

Uses of .htaccess :

1.  Disable directory Listing

Include following code if you want to disable folder files listing.

# Disable Directory Listing
Options All –Indexes

2.  Error Pages

You can set error pages for particular error.

Example :

errorDocument 400 http://www.yourdomain.com/error.html
errorDocument 401 http://www.yourdomain.com/error.html
errorDocument 404 http://www.yourdomain.com/error.html
errorDocument 500 http://www.yourdomain.com/error.html

If you want to turn on Rewrite Rules in Apache Server you have to write :

RewriteEngine On

If you want to turn off this rule, change the value to off. 

RewriteEngine on

RewriteEngine on

3.  Domain Redirection

To permanent redirect yourdomain.com to www.yourdomain.com, add following code :

RewriteCond %{HTTP_HOST} ^yourdomain.com
RewriteRule (.*) http://www.yourdomain.com /$1 [R=301,L]

4. Sub Domain Redirection

Sub domain redirection mapping to folder. Here www.yourdomain.com is connecting to website_folder folder.

RewriteCond %{HTTP_HOST} ^www\.yourdomain\.com$
RewriteCond %{REQUEST_URI} !^/website_folder/
RewriteRule (.*) /website_folder/$1

Here subdomain.yourdomain.com  is connecting to subdomain_folder folder.

RewriteCond %{HTTP_HOST} ^subdomain\.yourdomain\.com$
RewriteCond %{REQUEST_URI} !^/subdomain_folder/
RewriteRule (.*) /subdomain_folder/$1

5.  Old Domain Redirection
htaccess code for redirecting old domain(old.com) to new domain(new.com).

RewriteCond %{HTTP_HOST} ^old.com
RewriteRule (.*) http://www.new.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^www\.old\.com
RewriteRule (.*) http://www.new.com/$1 [R=301,L]

6.  Friendly URLs

Friendly and informative URLs help in Search Engine Ranking. URLs are the very important part of the search engine optimization process. 

Profile URL

Profile parameter allows [ a-zA-Z0-9_- ] these inputs. More help please read about Regular Expression 
http://gurutechnolabs.com/profile.php?username=test
to
http:// gurutechnolabs.com/test

RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?username=$1

Friends URL 

http://gurutechnolabs.com/friends.php?username=test
to
http://gurutechnolabs.com/friends/test

RewriteRule ^friends/([a-zA-Z0-9_-]+)$ friends.php?username=$1
RewriteRule ^friends/([a-zA-Z0-9_-]+)/$ friends.php?username=$1

Friends URL with Two Parameters 

Here the first parameter allows [a-zA-Z0-9_-] and second parameter allows only number [ 0-9 ]
http:// gurutechnolabs.com /friends.php?username=test&page=2
to
http:// gurutechnolabs.com /friends/test/2

RewriteRule ^friends/([a-zA-Z0-9_-]+)/([0-9]+)$ friends.php?username=$1&page=$2
RewriteRule ^friends/([a-zA-Z0-9_-]+)/([0-9]+)/$ friends.php?username=$1&page=$2

7.  Hiding File Extension

If you don’t want to display extension of web pages, just add following code :

Example :

http://www.yourdomain.com/index.html
to
http://www.yourdomain.com/index

RewriteRule ^([^/.]+)/?$ $1.html


Use of .htaccess for improving website speed and performance

1.  Enable Compression :

Compression is very useful for reducing the size of web pages.

There are two compression options :

  • Deflate :  Very easy to set up
  • GZIP : More powerful, You can pre compress the content

To enable Deflate mode, add following code in your .htaccess

<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript text/javascript
</ifmodule>

Enable GZIP compression mode

<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>

2.  Add Expire Headers : Enable Browser Caching

The Expire header is useful to cache data from the browser. It is helpful to speed up webpage because webpage can retrieve data from browser so no need to get it from the server that reduces HTTP requests.

<IfModule mod_expires.c>
 ExpiresActive on
 
# If you want to set default expire date
  ExpiresDefault "access plus 1 month"
 
# For html documents
  ExpiresByType text/html "access plus 0 seconds"
   
# Data
  ExpiresByType text/xml "access plus 0 seconds"
  ExpiresByType application/xml "access plus 0 seconds"
  ExpiresByType application/json "access plus 0 seconds"
 
# RSS feed
  ExpiresByType application/rss+xml "access plus 1 hour"
 
# Favicon (cannot be renamed)
  ExpiresByType image/x-icon "access plus 1 week"
 
# Media: images, video, audio
  ExpiresByType image/gif "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType image/jpg "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType video/ogg "access plus 1 month"
  ExpiresByType audio/ogg "access plus 1 month"
  ExpiresByType video/mp4 "access plus 1 month"
   
# CSS and JavaScript
  ExpiresByType text/css "access plus 1 year"
  ExpiresByType application/javascript "access plus 1 year"
  ExpiresByType text/javascript "access plus 1 year"
   
  <IfModule mod_headers.c>
   Header append Cache-Control "public"
  </IfModule>
   
</IfModule>

3.  Enable Keep Alive – TO decrease HTTP requests

By enabling Keep-Alive, your web server is telling the web browser that there is no need to make a separate request for each file it retrieves on a site.

<ifModule mod_headers.c> Header Set Connection Keep-alive <ifModule>

4.  Prevent Spam Bots to Crawl your website :

Sometimes the page load speed of your website can be reduced by bandwidth of you have available on your hosting plan. Sometimes spam boats take most of your bandwidth and your website become slowly.

So, it’s helpful to prevent spambots. 

<ifModule mod_setenvif.c>
#Set spammers referral as spambot
SetEnvifNoCase Referer spambot1.com spambot=yes
SetEnvifNoCase Referer spambot1.com spambot=yes
#Add as many as you want
Order allow,deny
Allow from all
Deny from env=spambot
<ifModule>

So, we can use .htaccess file for many purposes.

Happy Coding !!

The DevOps Zone is brought to you in partnership with Sonatype Nexus. Use the Nexus Suite to automate your software supply chain and ensure you're using the highest quality open source components at every step of the development lifecycle. Get Nexus today

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}