Advanced .htaccess examples

Advanced .htaccess examples

.htaccess is a file supported by apache web servers that allows us to do amazing things, like rewriting rules, changing default extension, redirecting url and more. This file can be placed in the website root folder or any subdirectories. Follow this tutorial step by step to get advanced .htaccess examples.

If you are using Wampserver under windows, you will need to enable the rewrite_module module.

Advanced .htaccess examples

1. Using .htaccess rewrite rules

Simple redirection

This .htaccess file will redirect to

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^contact-us$ contact.php [L]

Dynamique rewriting rules

This .htaccess file will redirect to

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^post-(.*)-([0-9]+)\.html$ post.php?post_name=$1&post_id=$2 [L]

Change extension for all file calls

This .htaccess file will redirect to

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*)\.jsp$ $1.php [L]

2. Url redirection using .htaccess

404 Redirect

Options +FollowSymLinks
RewriteEngine On
ErrorDocument 404 /404.php

Force non www to www

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^$
RewriteRule ^(.*)$1  [QSA,L,R=301]

Force using HTTPS

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

3. Password Protection with .htaccess and .htpasswd

You can protect your directory by a valid username and password using .htaccess and .htpasswd

First of all, generate a .htpasswd file that contain a username and password, you can use online generator like, copy and paste your user:password into a .htpasswd file.

In the case of user=ali and password=123456 w’ll got:


Place this file in your website directory.

Now create a .htaccess file with this content

AuthUserFile /var/www/vhosts/
AuthType Basic
AuthName "Authentication"
Require valid-user

Change /var/www/vhosts/ by the absolute path of the .htpasswd file.

Now place the .htaccess file into the directory that you want to protect.

404 Redirect, Apache, HTACCESS, HTACCESS Redirection, htpasswd, RewriteRule
comments powered by Disqus

Social Profiles

bewebdeveloper on facebook bewebdeveloper on twitter bewebdeveloper on google plus bewebdeveloper on vk bewebdeveloper on youtube bewebdeveloper on tumblr bewebdeveloper rss

Subscribe to our Newsletter




HTML Tutorials
CSS Tutorials