Basic .htaccess code samples

January 5th, 2010 by Alex Leave a reply »

Whether you are working on your website SEO or just looking a way to improve the user navigation, or help the search engine move to new pages, you’ll need to write redirects and rewrites via .htaccess

Here I’ll show the main htaccess tips and tricks.

To force the user view the http://www instead of http://, use this code:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

To force the user to browse the website via secure HTTPS port, use this code:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*) https://www.example.com/$1

If you don’t want to use HTTPS either, use

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTPS} =on
RewriteRule ^(.*) http://www.example.com/$1

If you wish to browse a certain folder in HTTPS, for example your ‘shop’ folder, use

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteCond %{REQUEST_URI} shop 
RewriteRule ^(.*)$ https://www.example.com/shop/$1 [R,L]

If you wish to run the script in another folder, but without the user knowing that. This example will open /hiddenfolder/home.html instead of actually /home/

RewriteEngine On 
RewriteBase /hiddenfolder
RewriteRule ^home/$  home.html

To include any file before the requested one

php_value auto_prepend_file somefile.php

And to include any file after the requested one

php_value auto_append_file somefile.php

If you have renamed a particular folder or category, use this code

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^/uglyoldfoldername/(.*)$ /newname/$1 [R]

If you renamed your .html files to .php, you can use this code

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)\.html$ $1.php [R=permanent]

If you decided to use nice urls, but you are using one .php file for that, you can use something like that

RewriteEngine on
RewriteRule ^cat/(.*)/(.*)/$ /index.php?cat=$1&id=$2 [L]

Or simply

RewriteEngine on
RewriteRule ^user/register/$ /user-register.php [L]

This page can be found by searching for:

htaccess sampleshtaccess sample



Comments are closed.