• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Web Server / Beginning Htaccess Programming

Beginning Htaccess Programming

February 17, 2011 by Rana Ahsan 4 Comments

htaccess tutorials

As far I saw and experienced, many developers always try to avoid using htaccess on their Linux environment based web applications. There is a good definite reason also behind this tradition. if you go and start reading the apache mod_rewrite documentation, you will find an line stating, “The price you have to pay is to accept complexity, because mod_rewrite’s major drawback is that it is not easy to understand and use for the beginner”. So, generally if you are interested to be proficient in htaccess programming, you should keep some patience and continuously practicing and experimenting it. Today, in this tutorial, I will try to focus on the very basics of htaccess programming to help you get a better quick start learning. I am assuming you are either an genuine beginner or want to get more clear about the basics.

What Is Htaccess?

Htaccess is the name of the default custom server configuration file used on Apache hosted HTTP servers. If you have used Apache on your local pc, then, you might know of a file named ‘httpd.conf’ which stores configurations that contains some instructions, how Apache will have to process a request. Htaccess file is actually a user level version for overriding those configurations.For a shared host, common configurations are same from this ‘httpd.conf’, but requirements may vary from user to user. These htaccess files help users fulfill their own requirements. It can also be referred as directory level configuration file. Because we can use this file on any number of directories we like and use different configuration settings for each of them.

This file’s physical name is “.htaccess” . If you are all time windows user, you might understand it as a file with no name and with extension ‘htaccess’. Actually, this is a Linux based convention, where all kind of .name(dot name) files are treated as hidden files. You can create this file on Linux based operating system very fine, without any problems. However, for windows operating system, you will face a problem while creating a new ‘.htaccess’ file . Try creating new text file and then to rename it, it will show you an windows error message mentioning ‘You must type a file name’. For avoiding this issue, simply open the file in notepad, go to “File->Save As” and then name it ‘.htaccess’ and save, this should work fine.

Uses Of Htaccess File:

Well, its a usual curiosity you might have right now on your mind, in which cases you should use this file and also what other uses it does provide that can be considerably attractive? Some of the most popular uses are as follows(which I will give examples of later on this tutorial):

  • Rewrite Urls: This is the most common uses .htaccess file help with.it parses the request urls of a specific format to a server script understandable format. Generally, it helps for using search engine friendly urls on a website easily without involving any server script coding where it passes the search engine friendly url’s request to corresponding server script/request handler with proper formatted data exists on url.
  • Authentication/Authorization Purpose: In your server, you will might want to develop some new applications/upgraded demo of existing applications and you don’t want to get those directories/sub domains found by anonymous users/visitors/search engines. Htaccess provides basic security mechanism(user name/password) to protect those contents from being public.
  • Redirect Urls: You will also can use htaccess commands for redirect some specific page(s) to somewhere else(some other internal/external links).

As you see the post title, I will primarily focus on ‘mod_rewrite’ options specially on this tutorial as this is the most common uses everyone needs to start with.

Enable Htaccess Rewrite Mode On Local Windows/XAMPP Environment:

I am using xampp on windows environment as my local server environment for development. I have noticed while working that, by default xampp doesn’t have the mode_rewrite enabled. We have to do this manually. So, I am sharing the tips to get that done so that you can get this easily.

Please go to your xampp root directory, among all other, find “\apache\conf” directory and navigate there. You will see the ‘httpd.conf’ file there. Open it with notepad, use the notepad’s find option to search for the word “mod_rewrite”. You will find few files . Some of them will have a “#” at the beginning of the line. This means these instruction lines are deactivated.(‘#’ is for comment syntax similar to “//” in php/c#/java etc programming languages). Activate those lines, just by removing the ‘#’ character. After this is complete, you should also checkout whether the override option is enabled or not. For that, search for ‘AllowOverride’ word. After get it, focus on the next word of it. If that is ‘None’, change that to ‘All’. Now, you should be fine with using htaccess mod_rewrite rules well.

Basic Htaccess File Structures:

Although There are a lot of custom and raw ways to start htaccess and it doesn’t force you to follow some strict rules to code, but we should, however follow some good structure that will give us most optimized and best results. Here is a basic htaccess file structure we should always use with:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    
    #don't rewrite for file and diretory access requests
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    
    # All Other rules goes here    

</IfModule>

<IfModule !mod_rewrite.c>
    # handles cases when rewrite isn't enabled
    ErrorDocument 404 /404.php
</IfModule>  

Htaccess Rewrite Examples:

Lets assume we want to parse a seo-friendly urls and need to feed the url data properly to correct request handler.

RewriteRule	     /	                                          index.php
RewriteRule	     /about	                                  index.php?page=about
RewriteRule	     /categories/^([\da-z-]+)$	  category.php?cat_name=$1
RewriteRule	     /products/^([\da-z-]+)$	          product.php?product_name=$1

We will now consider the reverse case also, where we will have to convert a query string based url to a proper handler. This are sometimes needed, specially in framework based application, where the frameworks defines a specific type of url structure to reach a request handler. Codeigniter is a good example of that kind of framework. The defined url structure is {controller_name}/{function_name}/{parameter(s)} (Codeigniter has this mechanism integrated with the framework. If you are a developer of this framework and having trouble with url rewriting/routing, you can refer to my another tutorial on codeigniter routing). If we need to get work a query string to feed in a specific controller function then, we will need such helps:

RewriteCond		                          %{QUERY_STRING} id=(.+)
RewriteRule	   ^send-email\.html/?(.*)$      /path_to/index.php/?controller_name/function_name/%1 [L]

Authorization Techniques In Htaccess:

If you want to make a directory protected from public access and want to provide basic user/password restricted, then should use this authentication code at the very beginning of the .htaccess file so that no other rules are executed/granted before authorization completes. Generally, it creates a session after authorization until you close your browser. If you close and open the browser again, it will require user/pass again. Here is the code samples for the htacess authorization :

AuthType Basic
AuthName "My Protected Area"
AuthUserFile /path/to/.htpasswd
Require valid-user

the password file can be any file containing the valid user name/password pair as like follows:

test:encrypted_passoword1
test:encrypted_passoword2

Notice that, the user name and password are divided by a ‘:’ character. The user name part is plain text and the password part is encrypted. So, you should use some htaccess password generator tool to get the passwords. Also, its best to use the password file names like “.htxxx” , because this kind of files aren’t accessed from http requests/browsers(otherwise if someone knows the file name somehow, they can access it via http easily and cause security vulnerabilities).

Redirect Urls In Htaccess:

Redirecting is quite easy and almost similar like routing/rewriting requests. Here is an example:

RewriteRule        /path/to/old_file1.html          new_url1 [R=301,L]
RewriteRule        /path/to/old_file2.html          new_url2 [R=301,L]

you can use any redirect specific code, if you want.

References:

As I already said before, you will need to keep some patience and try practicing continuously to be proficient in htaccess programming. To get some useful resources, please refer to the following links:

  • htaccess wiki
  • htaccess Apache documentation
  • htaccess tools

Hope this tutorial will may help you. Wish you best of luck to learn htaccess programming well. Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Web Server Tagged With: apache, htaccess

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. Sameer Kalia says

    June 26, 2012 at 2:29 pm

    please notify me on new posting

    Reply
    • Rana says

      June 27, 2012 at 10:31 pm

      Well, easy way to do so is to just subscribe :). For your help. I have submitted your email for subscription. Please activate it to get updated. Thanks.

      Reply
  2. visworlditsolution says

    August 2, 2017 at 11:31 pm

    can i use htaccess like Linux firewall ?if this is possible please show me code .

    Reply

Trackbacks

  1. Using mod_pagespeed module On Apache Servers | codesamplez.com says:
    March 3, 2011 at 2:59 am

    […] about using htaccess command directives, you are gladly invited to my another tutorial about htaccess programming for […]

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Beginning Codeigniter Application Development
    Beginning Codeigniter Application Development
  • Control HTML5 Audio With Jquery
    Control HTML5 Audio With Jquery
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023