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:
Hope this tutorial will may help you. Wish you best of luck to learn htaccess programming well. Happy coding 🙂
Discover more from CodeSamplez.com
Subscribe to get the latest posts sent to your email.
Sameer Kalia says
please notify me on new posting
Rana says
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.
visworlditsolution says
can i use htaccess like Linux firewall ?if this is possible please show me code .