You are using a browser which is not compatible with CSS (for more information, see Tara's tutorial). Because of this, it is possible that our website may not appear correctly in your browser. We apologise for the inconvenience, and recommend you upgrade your browser to one which is compatible with CSS. For more information, please visit our Browser Upgrade page.

4WebHelp

Rewriting URLs with mod_rewrite by Daniel

Last updated: 02/05/2012
Biography: Daniel has been interested in web design since 1999, when he first started designing a personal website. Since then, he has learnt much, and is interested in new web standards like XHTML and CSS, and in PHP.

Daniel is responsible for managing the 4WebHelp Forums, along with the forum moderators. He should be contacted for any modifications to your forum account (which you cannot do through the phpBB interface) and for any issues you may have with moderation.
See 9 more tutorials by Daniel

Background

Script Security

OK, you've just spent a whole day working on your latest script, which you're terribly proud of. It has all these great features and it looks great!! But have you thought about security? Often, you'll be using a script which selects information from an SQL database, and is called like this: script.php?category_id=5. What if some hacker (or script kiddie) comes along and types in script.php?category=hack_me? 95% (OK, I may be exaggerating, but you get the point) of scripts these days will spit out some kind of cryptic error like this (a search on Google reveals roughly 36 000 of these!):

You have an error in your sql syntax near 'your precious SQL query here'.

Now that he/she has noticed that your script isn't secure, they can start messing around and creating chaos. What can you do against this? First of all, make sure that all data is of the type it should be? Don't let people type in letters for an ID, and don't let them put a space in an email address, for example. Then make sure they can't "escape" from your SQL query by adding a ' to a parameter (category_id=hack_me' AND ...).

Usability

It is quite helpful for the user to have URLs like this: http://www.yoursite.com/Category_Name/, rather then http://www.yoursite.com/?category=12345. This will enable them to know what page they are loading even before it loads.

Search Engines

Unfortunately for us web developers/designers, (most) search engines are a real pain about dynamic pages. As soon as a page shows the slightest sign of being dynamic, they often ignore it. This enables them not to crawl through a 15 000 page site, and not to bog down your server at the same time! This means that they will often ignore URLs like this: script.php?category_id=1. But what if you want them to visit it? Well, the best solution would be to change that URL to script/Cat_Name/. But how are you going to do that? Read on to find out...

Apache and mod_rewrite

To use the "mod_rewrite" method of making "elegant" URLs, you will need Apache v. 1.2 or later, with the mod_rewrite module installed (mod stands for module). Ask your host if you are unsure as to whether it is installed.

So what is mod_rewrite?

mod_rewrite is an Apache module which takes care of rewriting URLs, thus transforming: http://www.yoursite.com/script.php?category_id=1 into http://www.yoursite.com/script/cat_1/

So how is this different from a classic redirection? Well, the main difference is that this "redirection" is totally transparent to the end-user: he/she will not know that the URL has been rewritten. It therefore requires no special browser or software on the visitor's end.

Let's start

Firstly, you'll need to put the following code in a file named .htaccess, in whichever directory you are dealing with:

RewriteEngine on

Now the mod_rewrite module has been turned on, and is ready to accept further instructions. The RewriteRule command is the root of the module, which tells mod_rewrite what to do. Here is its syntax:

RewriteRule Pattern Substitute (Optional Flags)

Here's an example:

RewriteRule /articles/([0-9]+) /articles.php?id=$1

This will replace http://www.yoursite.com/articles/1/ with http://www.yoursite.com/articles.php?id=1.

You don't have to limit yourself to numbers either, you can use [a-z] or [A-Z] too!

Here are some flags you can use:

  • f: send a 403 forbidden error to the browser
  • NC: make the rule case-insensitive
  • g: send a 410 gone error to the browser

Not only can you rewrite URLs using rules, but you can also add conditions to these rules, so they won't be executed in every case:

RewriteCond Test Condition

Here's an example of what you can do with conditions:

RewriteCond %{HTTP_USER_AGENT} ^Opera.*
RewriteRule ^/$ /index_opera.php [L]

RewriteCond %{HTTP_USER_AGENT} ^Netscape.*
RewriteRule ^/$ /index_netscape.php [L]

RewriteRule ^/$ /index.php [L]

This will load a special page for Opera and Netscape, and load a default page for people not using Netscape. Here are some variables you can use in your conditions:

  • HTTP_USER_AGENT (browser)
  • HTTP_REFERER (referring page)
  • HTTP_HOST (domain name - yoursite.domain.com)
  • TIME, TIME_YEAR, TIME_DAY, TIME_HOUR, TIME_MIN, TIME_SEC

Get to work!

Now that I've (hopefully) wet your appetite, you can get working on some great uses of mod_rewrite. Here are some examples of what can be achieved:

/books/456/ » /index.php?mode=books&id=456
/books/456/buy » /index.php?mode=buy&id=456
/book_456.html » /index.php?book=456

Of course, if you need any help with mod_rewrite, feel free to post in our Web Servers forum.

© 4WebHelp and Daniel

Latest comments on this tutorial
yomal
i need to change abc.mydomain.com/xyz.php?id3=se
to abc.mydomain.com/xyz/se/ with url rewriting.
here is my code in .htaccess (placed in abc folder)

Options +FollowSymLinks
RewriteEngine on
RewriteRule /xyz/([0-9a-zA-Z]+) /xyz.php?id3=$1

also tried without Options +FollowSymLinks

server - hosted server and they said mod_rewrite is enabled, but its not working. any advice pls?
Mizan
Please help me This code does not work

<IfModule mod_rewrite.c>

RewriteEngine On

RewriteRule ^catagary-([0-9]+)/p/([0-9]+)/(.*).html$ index.php?id=$1&page=$2 [NC,L]
RewriteRule ^catagary-([0-9]+)/(.*).html$ index.php?id=$1 [NC,L]

RewriteRule ^fileDownload/([0-9]+)/p/([0-9]+)/(.*).html$ view.php?id=$1 [L]
RewriteRule ^fileDownload/([0-9]+)/(.*).html$ view.php?id=$1 [L]

RewriteRule ^file/download/id/([0-9]+)/p/([0-9]+)/(.*)$ load.php?id=$1 [L]
RewriteRule ^file/download/id/([0-9]+)/(.*)$ load.php?id=$1 [L]

</IfModule>
A.S.Pardeshi
I am in the business of outsourcing. I have around 100 branded products for taking outsourced jobs. I have a list of the branded products keywords.

I have to design a page maybe in html or php whatever you may think fit with contents about outsourcing. let us assume this is the below paragraph:-

"We are doing outsourcing for the product xxxx since last many years. We have all the resources to manage the outsourcing of the product xxxx. So if you have to outsource the requirement for xxxx, kindly contact us with the details"


Now if you take my product list in a text file of 100 product list. I want xxxx in the above paragraph to be replaced by the product keyword typed in search engine.

Now let us take for example I have product "H*P La*se*rjet 10*20" suppose if anybody type in the search engine the above keyword and if that keyword is in my list then the xxxx in the above paragraph in yellow should get replaced with the keyword "H*P La*se*rjet 10*20" and presented to the search engine. The output will look similar to the one given below

"We are doing outsourcing for the product H*P La*se*rjet 10*20 since last many years. We have all the resources to manage the outsourcing of the product H*P La*se*rjet 10*20. So if you have to outsource the requirement for H*P La*se*rjet 10*20, kindly contact us with the details"



Please help me know how to do it ? Any help from SEO Experts is highly appreciated.

Kind Regards
Marcus
How do I exclude pages from being rewritten? Need to have a fixed page on  http://www.snusforum.com
Vilyamoy
Hello! great idea of color of this siyte!
Cindy
Used this on http://www.bloggerfly.net to offer free blogs for the URL's thanks.
rana farooq
hi all,
i want to convert url,
url:-      www.index.php
should look like         www.index.html
what should i have to do and do i need to put .htaccess file in www directory
dayton tire
Thank you.

Always yours, Tire Retreading Repair Shop.
Phil
Where do I put the .htaccess file to get it to work?

You put it in the root directory.
Mark
Thanks
Mark
Your Re-write tutorial helped me heaps.
Thanks.
juan
hi i'm trying to change the following:

https://www.site1.com/account_history_info.php/order_id/2425

to the following

https://www.site1.com/acc/id/2425

this is the rule i'm using (but it's not working):

RewriteRule ^/account_history_info.php/order_id/(0-9+)  /acc/id/$1

any comments? am i doing something wrong?
mizuki
telli> hey! thanx for reminding long forgotten tag, it came really helpful. hell i never figured out what it was good for and now i can see Smile hats off to telli Wink
Prabhjot
I would like to say thanks to the author of this article. I have been searching for such an article for a long time. I am new to PHP so it may take some time to me to understand this perfectly but this s one of the best and simplest article is have ever came across.

Thanks
Jason
...ahh, just had it in a bad section of my httpd.conf file. Inserted it into the appropriate <VirtualHost> and it worked like a charm.
Jason
I've got a similar problem.  My URL rewriting doesn't appear to be processing by the server. I'm trying to get this ghost URL:

http://www.mydomain.com/article/This-is-a-test

Redirected to this URL:

http://www.mydomain.com/article.html?id=This-is-a-test

...and here's the rule I'm using in my httpd.conf:

RewriteEngine On
RewriteRule ^article/([a-zA-Z0-9\-_\.\/]+)$ article/$1/ [R]
RewriteRule ^article/([a-zA-Z0-9\-_\.\/]+)/?$ article.html?id=$1 [L]

I have a feeling it's my regexp, but being new to it - I'm not sure. Anybody have any suggestions?
Goat Herder
Although most other people seem to be asking questions, I just wanted to leave some praise.

I just wanted to say that, with some confidence, I think this could be one of clearest and easiest-to-understand mod_rewrite tutorials on the web!

Thank you so much.
Ravish Kumar
hi
can anyine tell me how can i make a folder like

http://realestatecut.com/canada/

to look like..

http://canada.realestatecut.com/

without making a subdomain in the cpanel of the website
Bass
Hi is it possible to change a url from www.duk.org/index.php?side=support

to

www.duk.org/support

with rewrite?
Anonymous
Are you wetting or whetting our appetites? Wink
Nauman Ahmed
Hi,
For subdomains how url rewrite works.

1. http://www.sitename.com

2. http://my.sitename.com/abc.php?id=23

What syntax will be used for subdomain rewrite ?

Regards,
Robin
Hi
I have a very basic question how do I set it up so that I can use php in an html page and have it work.
ie for a navigation menu?
<script language="php">include("leftside.php");</script>
Thanks Robin
NHM Tanveer Hossain Khan (Hasan)
Hi i faced one problem when i mod_rewrite my url for example:

http://mydomain.com/mypage.html &#8212;> http://mydomain.com/mypage.php

if my url contains any Query String mod_rewrite just skip it&#8230;

Lets checkout the solution:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([A-zZ-a0-9\-_\.\/]*) start-application.php?url=$1&%{QUERY_STRING}

Thank you
Ben
Where do I put the .htaccess file to get it to work?
esu
I'm trying to write a Rule this way.
RewriteRule ^([0-9]+)/c$ sm.php?id=$1#c

but the # won't show in the url, it shows %23 and then it doesnt move to that section.

what can i do?
thx
natasha
hi
i have a website that picks all the data from DB just by  using variables in URL, i want to change them to SE friendly urls like html pages, but i want to make a general pattern for that since i cant take the gamble of defining each and every url in .htaccess file for site therefore help me ....
example url are like

localhost\mysite\showitems.php?maincat=games&letter=a&linkname=xbox

localhost\mysite\index.php?maincat=games&letter=a&linkname=xbox

-----------------
also pls tell me that when i will upload the site to webserver then what measures should i take to make it working for my site..
thanks for ur time

other
hello, I use ezSystem and another way for building friendly URL.
<a href="http://ez.no">ezSystem</a>


kepler
Hi,

I must be doing something wrong. From another referrer I am able to push the images; here what I've putted:


RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?example.com/.*$ [NC]
RewriteRule \.(gif|jpg|js)$ - [F]

I took this code from another website. It didn't work. So, I tryed:


Options +FollowSymlinks
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?sos-aid.com/.*$ [NC]
RewriteRule \.(gif|jpg|jpeg|js)$ \.images/Volunteers_1.jpg

Still doesn't work. What's wrong?

Regards,

Kepler
Vad
I am trying to get mod_rewrite working to replace /index.php?page=20  to /my-page.html

Here what I have in my .htaccess:
RewriteEngine on
RewriteBase /
RewriteRule /my-page.html /index.php?page=20

It does not work, am I doing anything wrong?

Please help,

Vad
Daniel, 4WebHelp Team Member
Sam: You're using relative paths to the images. You'll have to change them since the browser thinks you're in a subdirectory of "list" now.
Sam
Hi Daniel,

Output for http://www.tomdooley.info/tom/list/1 is not equal to http://www.tomdooley.info/tom/list.php?partid=1

The images are missing. Still trying to figure out the problem.

Sam

Daniel, 4WebHelp Team Member
Sam: I just tested it and it seems to work fine on your site. What's wrong?
shant
hello guys ..
nice article
but i have a question can i redirect my whole website from http to https and remove the www from the url.
like http://www.shant.com
to
https://shant.com

i need the answer soon
thnaks again
Marta Cillero
Problem is solved now. The code was ok, there was something wrong in the server, I told our provider, and now it works.

Its very usefull! Thank you for your help.
Im going to use it also as a spam filter, to avoid spammers around my weblog:


RewriteEngine On
RewriteCond %{HTTP_REFERER} "!^http://sitename.com/.*$" [NC]
RewriteCond %{REQUEST_URI} ".*wp-comments-post.php$"
RewriteRule .* - [F]

I hope it works... nowdays spammers are so advanced that they could even cheat on Apache.
Marta
I just tried my .htaccess with only this one line:

RewriteEngine On

and get same 500 error, so maybe mod_rewrite module is not fully active?

I have no access to httpd.conf, I have a hosting account
Marta Cillero
Thank you for your fast answer
Yes, I looked at phpinfo() and I see "mod_rewrite" in Loaded modules from apache, so i guess its installed.

I am able to use .htacces for authentication with "mod_access"

Could it be my apache version (Apache/1.3.20) or something to do with cobalt raq 550 ?
Daniel, 4WebHelp Team Member
Marta: Have you made sur mod_rewrite is installed?
Marta Cillero
Im trying to use mod_rewrite in a .htaccess to convert the URLs of my weblog wordpress:

index.php?category_name=

to:

category/

This is the code:
--------------------------
RewriteEngine On
RewriteBase /
RewriteRule ^category/(.*)/(feed|rdf|rss|rss2|atom)/?$ /wp-feed.php?category_name=$1&feed=$2 [QSA]
RewriteRule ^category/?(.*) /index.php?category_name=$1 [QSA]
RewriteRule ^author/(.*)/(feed|rdf|rss|rss2|atom)/?$ /wp-feed.php?author_name=$1&feed=$2 [QSA]
RewriteRule ^author/?(.*) /index.php?author_name=$1 [QSA]
RewriteRule ^([0-9]{1,2})/?([0-9]{1,2})?/?([0-9]{4})?/?([_0-9a-z-]+)?/?([0-9]+)?/?$ /index.php?day=$1&monthnum=$2&year=$3&name=$4&page=$5 [QSA]
RewriteRule ^([0-9]{1,2})/?([0-9]{1,2})/([0-9]{4})/([_0-9a-z-]+)/(feed|rdf|rss|rss2|atom)/?$ /wp-feed.php?day=$1&monthnum=$2&year=$3&name=$4&feed=$5 [QSA]
RewriteRule ^([0-9]{1,2})/?([0-9]{1,2})/([0-9]{4})/([_0-9a-z-]+)/trackback/?$ /wp-trackback.php?day=$1&monthnum=$2&year=$3&name=$4 [QSA]
RewriteRule ^feed/?([_0-9a-z-]+)?/?$ /wp-feed.php?feed=$1 [QSA]
RewriteRule ^comments/feed/?([_0-9a-z-]+)?/?$ /wp-feed.php?feed=$1&withcomments=1 [QSA]
----------------------------------------
Well, im not very skilled with Apache, im getting 500 server error when executing any page.
Maybe the code is ok, and the problem is in the server (im using cobalt raq 550)?
or
maybe the problem is the Apache version on the server (Apache/1.3.20)?

Could be something to do with relative paths?

I would really apreciate your help... please, anybody knows?
kac
need more examples!!!
MasterShake
If you're like me and couldn't get that to work (conflicts with something else you have setup, like subdomains), try rewriting the base first (and separatly):

RewriteBase /
RewriteRule articles/([0-9]+) articles.php?id=$1
Daniel, 4WebHelp Team Member
Oops. Thanks for letting me know - fixed. The problem was the same one as I mentioned in my PM.
adam
RewriteRule /articles/([0-9]+) /articles.php?id=

should be:

RewriteRule /articles/([0-9]+) /articles.php?id=$1

Add a new comment

This page is © Copyright 2002-2017, 4WebHelp. It may not be reproduced without 4WebHelp's prior permission.