DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

How to Use the .htaccess File Effectively

The .htaccess file is the config file for web servers running the Apache Web Server and is useful for configuring and redirecting the Apache Web Server file system.

Anjana Ratadiya user avatar by
Anjana Ratadiya
·
Aug. 24, 18 · Tutorial
Like (5)
Save
Tweet
Share
27.59K Views

Join the DZone community and get the full member experience.

Join For Free

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

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

There are many uses for the .htaccess files. Here, I will discuss creating them and their uses.

Creating an .htaccess File

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

Uses for .htaccess

1. Disable Directory Listings

Include the following code if you want to disable the folder files listings.

# Disable Directory Listing
Options All –Indexes

2. Error Pages

You can set error pages for the 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 the Apache Server, you have to write:

RewriteEngine on 

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

RewriteEngine on

3. Domain Redirection

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

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

4. Subdomain Redirection

You can also perform subdomain redirection mapping to the folder. Here www.yourdomain.com is connecting to the 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 the subdomain_folder folder.

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

5. Old Domain Redirection

The .htaccess code for redirecting an old domain (old.com) to a 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 rankings. URLs are a very important part of the search engine optimization process.

Profile URL

Profile parameters [ a-zA-Z0-9_-] turns this input (for more help, please read about Regular Expressions):

http://gurutechnolabs.com/profile.php?username=test

into

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

Say you don’t want to display an extension a web page. 

Example :

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

to 

http://www.yourdomain.com/index

Just add the following code :

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 used to cache data from the browser. It is helpful to speed up webpage because webpage can retrieve data from the 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. Also, make sure to code it in such way that it will reduce HTTP requests.

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

4. Prevent Spam Bots From Crawling Your Website

Sometimes the page load speed of your website can be reduced by the bandwidth you have available on your hosting plan. Sometimes spam boats take most of your bandwidth and your website becomes 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 the .htaccess file for many purposes.

Happy coding!

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Required Knowledge To Pass AWS Certified Solutions Architect — Professional Exam
  • mTLS Everywere
  • Strategies for Kubernetes Cluster Administrators: Understanding Pod Scheduling
  • Cucumber.js Tutorial With Examples For Selenium JavaScript

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: