.htaccess tutorial with mod_rewrite

Published on January 01, 2007

The .htaccess file is used if you are using the Apache web server and need to add functionality to your web site like hide actual URLs, redirect web pages, redirect whole directories, force WWW to appear in the URL or vice versa, etc.

How to redirect all http (port 80) requests to https (port 443)

Sometimes you may need to allow only http requests via SSL and redirect all http requests on port 80 (http) to 443 (https).

In order to force all port 80 requests to port 443, edit the file .htaccess and add these lines:

RewriteEngine on
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^/(.*) https://%{SERVER_NAME}/$1 [NC,R,L]

How to force WWW in the URL

The URLs www.aruljohn.com and aruljohn.com are viewed differently by most search engines even though both usually point to the same place. It would be a good idea to force all requests to the same URL with a 301 redirect.

In order to redirect aruljohn.com to www.aruljohn.com edit the file `.htaccess and add these lines:

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

How to remove WWW from the URL

Read the above section. To force all requests to www.aruljohn.com to be redirected to aruljohn.com edit the file `.htaccess and add these lines:

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

How to mask dynamic PHP or CGI images with image extensions (GIF, JPG, PNG)

Some discussion forms like phpBB and InvisionBoard prevent display of images if the extension of the image does not end in the regular image formats like GIF, JPG, PNG, etc.

I want to post my dynamic PHP image modernart.php in a forum that allows only valid image file extensions, so I make the PHP script appear as a PNG file.

phpBB >> http://aruljohn.com/sig/modernart.png >> http://aruljohn.com/sig/modernart.php

Edit the file `.htaccess and add these lines:

RewriteEngine On
RewriteRule modernart.png modernart.php

Now when I paste this "image" in any phpBB discussion board, it is accepted as a valid image! See it in action here below:

arul modern art modernart.png (actually translates to modernart.php)

Related Posts

If you have any questions, please contact me at arulbOsutkNiqlzziyties@gNqmaizl.bkcom. You can also post questions in our Facebook group. Thank you.

Disclaimer: Our website is supported by our users. We sometimes earn affiliate links when you click through the affiliate links on our website.

Published on January 01, 2007

← Previous Post
Installing X Window on Debian

Next Post →
SSI Includes