Htaccess url rewriting

What is .htaccess file ?

.htaccess is a configuration file of apache web server. When we put it to our server root directory. Apache web server load this and alter its default functionality like redirecting to some location, ask password to open a page etc.

In this tutorials we will cover some important parts of htaccess

  • Redirect the user to different page
  • Password protect a specific directory
  • Block users by IP
  • Preventing hot linking of your images
  • Rewrite URIs
  • Specify your own Error Documents


Removing Extensions

If you want to remove .php extension from your page ex: to ,use below code inside .htaccess file

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

If you want to remove the .html extension from a html file for example to you simply have to alter the last line from the code above to match the filename:

RewriteRule ^([^\.]+)$ $1.html [NC,L]

Now you can directly link pages without any extension as shown below example

<a title="about" href="">about</a>


Password protect a specific directory

Sometimes we need to deny access from unauthorized user to access some page in our website .So, to allow only user who have successfully authorized via login to access web pages find below htaccess tutorial

For this requirement we need 2 files 1) .htaccess 2) .htpasswd file

inside .htaccess file ,put below code

AuthType Basic
AuthName "restricted area"
AuthUserFile /home/user/html/protected-dir/.htpasswd
require valid-user

This will protect a directory called ‘protected-dir’ on root level. Above mentioned ‘user’ is your server Document Root .If you don’t sure what it should be , get a value from phpinfo() function and find there value of DOCUMENT_ROOT .


The .htpasswd Code


Above should mention allowed user:password combination one per line . Password should MD5 hash for security reason.

Online Web Development Training,Video Tutorials