Introduction
URL rewriting can be one of the best and quickest ways to improve the usability and search friendliness of your site. It can also be the source of near-unending misery and suffering. Definitely worth playing carefully with it - lots of testing is recommended. With great power comes great responsibility, and all that.
There are several other guides on the web already, that may suit your needs better than this one.
- Apache URL Rewriting Guide - The best guide around
Before reading on, you may find it helpful to have the mod_rewrite cheat sheet and/or the regular expressions cheat sheet handy. A basic grasp of the concept of regular expressions would also be very helpful.
What is "URL Rewriting"?
Most dynamic sites include variables in their URLs that tell the site what information to show the user. Typically, this gives URLs like the following, telling the relevant script on a site to load product number 7.
http://www.pets.com/show_a_product.php?product_id=7
The problems with this kind of URL structure are that the URL is not at all memorable. It's difficult to read out over the phone (you'd be surprised how many people pass URLs this way). Search engines and users alike get no useful information about the content of a page from that URL. You can't tell from that URL that that page allows you to buy a Norwegian Blue Parrot (lovely plumage). It's a fairly standard URL - the sort you'd get by default from most CMSes. Compare that to this URL:
http://www.pets.com/products/7/
Clearly a much cleaner and shorter URL. It's much easier to remember, and vastly easier to read out. That said, it doesn't exactly tell anyone what it refers to. But we can do more:
http://www.pets.com/parrots/norwegian-blue/
Now we're getting somewhere. You can tell from the URL, even when it's taken out of context, what you're likely to find on that page. Search engines can split that URL into words (hyphens in URLs are treated as spaces by search engines, whereas underscores are not), and they can use that information to better determine the content of the page. It's an easy URL to remember and to pass to another person.
Unfortunately, the last URL cannot be easily understood by a server without some work on our part. When a request is made for that URL, the server needs to work out how to process that URL so that it knows what to send back to the user. URL rewriting is the technique used to "translate" a URL like the last one into something the server can understand.
Platforms and Tools
Depending on the software your server is running, you may already have access to URL rewriting modules. If not, most hosts will enable or install the relevant modules for you if you ask them very nicely.
Apache is the easiest system to get URL rewriting running on. It usually comes with its own built-in URL rewriting module, mod_rewrite, enabled, and working with mod_rewrite is as simple as uploading correctly formatted and named text files.
IIS, Microsoft's server software, doesn't include URL rewriting capability as standard, but there are add-ons out there that can provide this functionality. ISAPI_Rewrite is the one I recommend working with, as I've so far found it to be the closest to mod_rewrite's functionality. Instructions for installing and configuring ISAPI_Rewrite can be found at the end of this article.
The code that follows is based on URL rewriting using mod_rewrite.
Basic URL Rewriting
To begin with, let's consider a simple example. We have a website, and we have a single PHP script that serves a single page. Its URL is:
http://www.pets.com/pet_care_info_07_07_2008.php
We want to clean up the URL, and our ideal URL would be:
http://www.pets.com/pet-care/
In order for this to work, we need to tell the server to internally redirect all requests for the URL "pet-care" to "pet_care_info_07_07_2008.php". We want this to happen internally, because we don't want the URL in the browser's address bar to change.
To accomplish this, we need to first create a text document called ".htaccess" to contain our rules. It must be named exactly that (not ".htaccess.txt" or "rules.htaccess"). This would be placed in the root directory of the server (the same folder as "pet_care_info_07_07_2008.php" in our example). There may already be an .htaccess file there, in which case we should edit that rather than overwrite it.
The .htaccess file is a configuration file for the server. If there are errors in the file, the server will display an error message (usually with an error code of "500"). If you are transferring the file to the server using FTP, you must make sure it is transferred using the ASCII mode, rather than BINARY. We use this file to perform 2 simple tasks in this instance - first, to tell Apache to turn on the rewrite engine, and second, to tell apache what rewriting rule we want it to use. We need to add the following to the file:
RewriteEngine On # Turn on the rewriting engine
RewriteRule ^pet-care/?$ pet_care_info_01_02_2008.php [NC,L] # Handle requests for "pet-care"
A couple of quick items to note - everything following a hash symbol in an .htaccess file is ignored as a comment, and I'd recommend you use comments liberally; and the "RewriteEngine" line should only be used once per .htaccess file (please note that I've not included this line from here onwards in code example).
The "RewriteRule" line is where the magic happens. The line can be broken down into 5 parts:
- RewriteRule - Tells Apache that this like refers to a single RewriteRule.
- ^/pet-care/?$ - The "pattern". The server will check the URL of every request to the site to see if this pattern matches. If it does, then Apache will swap the URL of the request for the "substitution" section that follows.
- pet_care_info_01_02_2003.php - The "substitution". If the pattern above matches the request, Apache uses this URL instead of the requested URL.
- [NC,L] - "Flags", that tell Apache how to apply the rule. In this case, we're using two flags. "NC", tells Apache that this rule should be case-insensitive, and "L" tells Apache not to process any more rules if this one is used.
- # Handle requests for "pet-care" - Comment explaining what the rule does (optional but recommended)
The rule above is a simple method for rewriting a single URL, and is the basis for almost all URL rewriting rules.
Patterns and Replacements
The rule above allows you to redirect requests for a single URL, but the real power of mod_rewrite comes when you start to identify and rewrite groups of URLs based on patterns they contain.
Let's say you want to change all of your site URLs as described in the first pair of examples above. Your existing URLs look like this:
http://www.pets.com/show_a_product.php?product_id=7
And you want to change them to look like this:
http://www.pets.com/products/7/
Rather than write a rule for every single product ID, you of course would rather write one rule to manage all product IDs. Effectively you want to change URLs of this format:
http://www.pets.com/show_a_product.php?product_id={a number}
And you want to change them to look like this:
http://www.pets.com/products/{a number}/
In order to do so, you will need to use "regular expressions". These are patterns, defined in a specific format that the server can understand and handle appropriately. A typical pattern to identify a number would look like this:
[0-9]+
The square brackets contain a range of characters, and "0-9" indicates all the digits. The plus symbol indicates that the pattern will idenfiy one or more of whatever precedes the plus - so this pattern effectively means "one or more digits" - exactly what we're looking to find in our URL.
The entire "pattern" part of the rule is treated as a regular expression by default - you don't need to turn this on or activate it at all.
RewriteRule ^products/([0-9]+)/?$ show_a_product.php?product_id=$1 [NC,L] # Handle product requests
The first thing I hope you'll notice is that we've wrapped our pattern in brackets. This allows us to "back-reference" (refer back to) that section of the URL in the following "substitution" section. The "$1" in the substitution tells Apache to put whatever matched the earlier bracketed pattern into the URL at this point. You can have lots of backreferences, and they are numbered in the order they appear.
And so, this RewriteRule will now mean that Apache redirects all requests for domain.com/products/{number}/ to show_a_product.php?product_id={same number}.
Regular Expressions
A complete guide to regular expressions is rather beyond the scope of this article. However, important points to remember are that the entire pattern is treated as a regular expression, so always be careful of characters that are "special" characters in regular expressions.
The most instance of this is when people use a period in their pattern. In a pattern, this actually means "any character" rather than a literal period, and so if you want to match a period (and only a period) you will need to "escape" the character - precede it with another special character, a backslash, that tells Apache to take the next character to be literal.
For example, this RewriteRule will not just match the URL "rss.xml" as intended - it will also match "rss1xml", "rss-xml" and so on.
RewriteRule ^rss.xml$ rss.php [NC,L] # Change feed URL
This does not usually present a serious problem, but escaping characters properly is a very good habit to get into early. Here's how it should look:
RewriteRule ^rss\.xml$ rss.php [NC,L] # Change feed URL
This only applies to the pattern, not to the substitution. Other characters that require escaping (referred to as "metacharacters") follow, with their meaning in brackets afterwards:
- . (any character)
- * (zero of more of the preceding)
- + (one or more of the preceding)
- {} (minimum to maximum quantifier)
- ? (ungreedy modifier)
- ! (at start of string means "negative pattern")
- ^ (start of string, or "negative" if at the start of a range)
- $ (end of string)
- [] (match any of contents)
- - (range if used between square brackets)
- () (group, backreferenced group)
- | (alternative, or)
- \ (the escape character itself)
Using regular expressions, it is possible to search for all sorts of patterns in URLs and rewrite them when they match. Time for another example - we wanted earlier to be able to indentify this URL and rewrite it:
http://www.pets.com/parrots/norwegian-blue/
And we want to be able to tell the server to interpret this as the following, but for all products:
http://www.pets.com/get_product_by_name.php?product_name=norwegian-blue
And we can do that relatively simply, with the following rule:
RewriteRule ^parrots/([A-Za-z0-9-]+)/?$ get_product_by_name.php?product_name=$1 [NC,L] # Process parrots
With this rule, any URL that starts with "parrots" followed by a slash (parrots/), then one or more (+) of any combination of letters, numbers and hyphens ([A-Za-z0-9-]) (note the hyphen at the end of the selection of characters within square brackets - it must be added there to be treated literally rather than as a range separator). We reference the product name in brackets with $1 in the substitution.
We can make it even more generic, if we want, so that it doesn't matter what directory a product appears to be in, it is still sent to the same script, like so:
RewriteRule ^[A-Za-z-]+/([A-Za-z0-9-]+)/?$ get_product_by_name.php?product_name=$1 [NC,L] # Process all products
As you can see, we've replaced "parrots" with a pattern that matches letter and hyphens. That rule will now match anything in the parrots directory or any other directory whose name is comprised of at least one or more letters and hyphens.
Flags
Flags are added to the end of a rewrite rule to tell Apache how to interpret and handle the rule. They can be used to tell apache to treat the rule as case-insensitive, to stop processing rules if the current one matches, or a variety of other options. They are comma-separated, and contained in square brackets. Here's a list of the flags, with their meanings (this information is included on the cheat sheet, so no need to try to learn them all).
- C (chained with next rule)
- CO=cookie (set specified cookie)
- E=var:value (set environment variable var to value)
- F (forbidden - sends a 403 header to the user)
- G (gone - no longer exists)
- H=handler (set handler)
- L (last - stop processing rules)
- N (next - continue processing rules)
- NC (case insensitive)
- NE (do not escape special URL characters in output)
- NS (ignore this rule if the request is a subrequest)
- P (proxy - i.e., apache should grab the remote content specified in the substitution section and return it)
- PT (pass through - use when processing URLs with additional handlers, e.g., mod_alias)
- R (temporary redirect to new URL)
- R=301 (permanent redirect to new URL)
- QSA (append query string from request to substituted URL)
- S=x (skip next x rules)
- T=mime-type (force specified mime type)
Moving Content
RewriteRule ^article/?$ http://www.new-domain.com/article/ [R,NC,L] # Temporary Move
Adding an "R" flag to the flags section changes how a RewriteRule works. Instead of rewriting the URL internally, Apache will send a message back to the browser (an HTTP header) to tell it that the document has moved temporarily to the URL given in the "substitution" section. Either an absolute or a relative URL can be given in the substitution section. The header sent back includea a code - 302 - that indicates the move is temporary.
RewriteRule ^article/?$ http://www.new-domain.com/article/ [R=301,NC,L] # Permanent Move
If the move is permanent, append "=301" to the "R" flag to have Apache tell the browser the move is considered permanent. Unlike the default "R", "R=301" will also tell the browser to display the new address in the address bar.
This is one of the most common methods of rewriting URLs of items that have moved to a new URL (for example, it is in use extensively on this site to forward users to new post URLs whenever they are changed).
Conditions
Rewrite rules can be preceded by one or more rewrite conditions, and these can be strung together. This can allow you to only apply certain rules to a subset of requests. Personally, I use this most often when applying rules to a subdomain or alternative domain as rewrite conditions can be run against a variety of criteria, not just the URL. Here's an example:
RewriteCond %{HTTP_HOST} ^addedbytes\.com [NC]
RewriteRule ^(.*)$ http://www.addedbytes.com/$1 [L,R=301]
The rewrite rule above redirects all requests, no matter what for, to the same URL at "www.addedbytes.com". Without the condition, this rule would create a loop, with every request matching that rule and being sent back to itself. The rule is intended to only redirect requests missing the "www" URL portion, though, and the condition preceding the rule ensures that this happens.
The condition operates in a similar way to the rule. It starts with "RewriteCond" to tell mod_rewrite this line refers to a condition. Following that is what should actually be tested, and then the pattern to test. Finally, the flags in square brackets, the same as with a RewriteRule.
The string to test (the second part of the condition) can be a variety of different things. You can test the domain being requested, as with the above example, or you could test the browser being used, the referring URL (commonly used to prevent hotlinking), the user's IP address, or a variety of other things (see the "server variables" section for an outline of how these work).
The pattern is almost exactly the same as that used in a RewriteRule, with a couple of small exceptions. The pattern may not be interpreted as a pattern if it starts with specific characters as described in the following "exceptions" section. This means that if you wish to use a regular expression pattern starting with <, >, or a hyphen, you should escape them with the backslash.
Rewrite conditions can, like rewrite rules, be followed by flags, and there are only two. "NC", as with rules, tells Apache to treat the condition as case-insensitive. The other available flag is "OR". If you only want to apply a rule if one of two conditions match, rather than repeat the rule, add the "OR" flag to the first condition, and if either match then the following rule will be applied. The default behaviour, if a rule is preceded by multiple conditions, is that it is only applied if all rules match.
Exceptions and Special Cases
Rewrite conditions can be tested in a few different ways - they do not need to be treated as regular expression patterns, although this is the most common way they are used. Here are the various ways rewrite conditons can be processed:
- <Pattern (is test string lower than pattern)
- >Pattern (is test string greater than pattern)
- =Pattern (is test string equal to pattern)
- -d (is test string a valid directory)
- -f (is test string a valid file)
- -s (is test string a valid file with size greater than zero)
- -l (is test string a symbolic link)
- -F (is test string a valid file, and accessible (via subrequest))
- -U (is test string a valid URL, and accessible (via subrequest))
Server Variables
Server variables are a selection of items you can test when writing rewrite conditions. This allows you to apply rules based on all sorts of request parameters, including browser identifiers, referring URL or a multitude of other strings. Variables are of the following format:
%{VARIABLE_NAME}
And "VARIABLE_NAME" can be replaced with any one of the following items:
- HTTP Headers
- HTTP_USER_AGENT
- HTTP_REFERER
- HTTP_COOKIE
- HTTP_FORWARDED
- HTTP_HOST
- HTTP_PROXY_CONNECTION
- HTTP_ACCEPT
- Connection Variables
- REMOTE_ADDR
- REMOTE_HOST
- REMOTE_USER
- REMOTE_IDENT
- REQUEST_METHOD
- SCRIPT_FILENAME
- PATH_INFO
- QUERY_STRING
- AUTH_TYPE
- Server Variables
- DOCUMENT_ROOT
- SERVER_ADMIN
- SERVER_NAME
- SERVER_ADDR
- SERVER_PORT
- SERVER_PROTOCOL
- SERVER_SOFTWARE
- Dates and Times
- TIME_YEAR
- TIME_MON
- TIME_DAY
- TIME_HOUR
- TIME_MIN
- TIME_SEC
- TIME_WDAY
- TIME
- Special Items
- API_VERSION
- THE_REQUEST
- REQUEST_URI
- REQUEST_FILENAME
- IS_SUBREQ
Working With Multiple Rules
The more complicated a site, the more complicated the set of rules governing it can be. This can be problematic when it comes to resolving conflicts between rules. You will find this issue rears its ugly head most often when you add a new rule to a file, and it doesn't work. What you may find, if the rule itself is not at fault, is that an earlier rule in the file is matching the URL and so the URL is not being tested against the new rule you've just added.
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ get_product_by_name.php?category_name=$1&product_name=$2 [NC,L] # Process product requests
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ get_blog_post_by_title.php?category_name=$1&post_title=$2 [NC,L] # Process blog posts
In the example above, the product pages of a site and the blog post pages have identical patterns. The second rule will never match a URL, because anything that would match that pattern will have already been matched by the first rule.
There are a few ways to work around this. Several CMSes (including wordpress) handle this by adding an extra portion to the URL to denote the type of request, like so:
RewriteRule ^products/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ get_product_by_name.php?category_name=$1&product_name=$2 [NC,L] # Process product requests
RewriteRule ^blog/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ get_blog_post_by_title.php?category_name=$1&post_title=$2 [NC,L] # Process blog posts
You could also write a single PHP script to process all requests, which checked to see if the second part of the URL matched a blog post or a product. I usually go for this option, as while it may increase the load on the server slightly, it gives much cleaner URLs.
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ get_product_or_blog_post.php?category_name=$1&item_name=$2 [NC,L] # Process product and blog requests
There are certain situations where you can work around this issue by writing more precise rules and ordering your rules intelligently. Imagine a blog where there were two archives - one by topic and one by year.
RewriteRule ^([A-Za-z0-9-]+)/?$ get_archives_by_topic.php?topic_name=$1 [NC,L] # Get archive by topic
RewriteRule ^([A-Za-z0-9-]+)/?$ get_archives_by_year.php?year=$1 [NC,L] # Get archive by year
The above rules will conflict. Of course, years are numeric and only 4 digits, so you can make that rule more precise, and by running it first the only type of conflict you cound encounter would be if you had a topic with a 4-digit number for a name.
RewriteRule ^([0-9]{4})/?$ get_archives_by_year.php?year=$1 [NC,L] # Get archive by year
RewriteRule ^([A-Za-z0-9-]+)/?$ get_archives_by_topic.php?topic_name=$1 [NC,L] # Get archive by topic
mod_rewrite
Apache's mod_rewrite comes as standard with most Apache hosting accounts, so if you're on shared hosting, you are unlikely to have to do anything. If you're managing your own box, then you most likely just have to turn on mod_rewrite. If you are using Apache1, you will need to edit your httpd.conf file and remove the leading '#' from the following lines:
#LoadModule rewrite_module modules/mod_rewrite.so
#AddModule mod_rewrite.c
If you are using Apache2 on a Debian-based distribution, you need to run the following command and then restart Apache:
sudo a2enmod rewrite
Other distubutions and platforms differ. If the above instructions are not suitable for your system, then Google is your friend. You may need to edit your apache2 configuration file and add "rewrite" to the "APACHE_MODULES" list, or edit httpd.conf, or even download and compile mod_rewrite yourself. For the majority, however, installation should be simple.
ISAPI_Rewrite
ISAPI_Rewrite is a URL rewriting plugin for IIS based on mod_rewrite and is not free. It performs most of the same functionality as mod_rewrite, and there is a good quality ISAPI_Rewrite forum where most common questions are answered. As ISAPI_Rewrite works with IIS, installation is relatively simple - there are installation instructions available.
ISAPI_Rewrite rules go into a file named httpd.ini. Errors will go into a file named httpd.parse.errors by default.
Leading Slashes
I have found myself tripped up numerous times by leading slashes in URL rewriting systems. Whether they should be used in the pattern or in the substitution section of a RewriteRule or used in a RewriteCond statement is a constant source of frustration to me. This may be in part because I work with different URL rewriting engines, but I would advise being careful of leading slashes - if a rule is not working, that's often a good place to start looking. I never include leading slashes in mod_rewrite rules and always include them in ISAPI_Rewrite.
Sample Rules
To redirect an old domain to a new domain:
RewriteCond %{HTTP_HOST} old_domain\.com [NC]
RewriteRule ^(.*)$ http://www.new_domain.com/$1 [L,R=301]
To redirect all requests missing "www" (yes www):
RewriteCond %{HTTP_HOST} ^domain\.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]
To redirect all requests with "www" (no www):
RewriteCond %{HTTP_HOST} ^www\.domain\.com [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]
Redirect old page to new page:
RewriteRule ^old-url\.htm$ http://www.domain.com/new-url.htm [NC,R=301,L]
Useful Links
- Regular Expression Testing Tool
- mod_rewrite Forum
- Webapplication Firewall
- .htaccess Tricks
- mod_rewrite Cheat Sheet
- Regular Expressions Cheat Sheet
Summary
Hopefully if you've made it this far you now have a clear understanding of what URL rewriting is and how to add it to your site. It is worth taking the time to become familiar with - it can benefit your SEO efforts immediately, and increase the usability of your site.

196 Comments
Nice tutorial, Dave. Very thorough!
#1, Joe Dolson, United States, 4 August 2008. Reply to this.
Great tutorial. Maybe even in the über-tutorial category! Many thanks!
The "Stupid htaccess tricks" page is anything but stupid, and would make a nice addition to your list of useful links, IMO. URL =
http://perishablepress.com/press/2006/01/10/stupid-htaccess-tricks
#2, David Reimer, United Kingdom, 4 August 2008. Reply to this.
Thanks Joe, David. I've added that link in - amazed I'd not seen that before - what a great resource!
#3, DaveChild, United Kingdom, 4 August 2008. Reply to this.
URL rewriting has always been a topic of interest for me and every more topic or article about it and about .htaccess always a must-read me.
Certainly this article has been of quite much help for me. Thanks.
#4, Subash, Unknown, 4 August 2008. Reply to this.
Really great article. Sorry for getting off the subject, but I am unable to print it out (using FF3 or IE6). Only the first page prints out. I'm guessing it's a javascript thing? Is it just me?
#5, jim d, United States, 4 August 2008. Reply to this.
You put a lot of time into this article! Great work. URL rewriting, specifically mod_rewrite, is such a powerful tool. This is very comprehensive.
#6, Matt, United States, 4 August 2008. Reply to this.
Subash: Likewise - mod_rewrite is one of those tools that just draws you in :)
jim: Thanks. I'm looking into the printing now. It should be fine - might be a problem with the <code> blocks ...
Matt: Indeed I did. This has been the result of several months of on-off addition. It was getting to the stage where I was nitpicking and adding small sections (looking at adding Zeus rules, for example, or alternatives to ISAPI_Rewrite on IIS), but better to get it out in the wild where people can use it than have it sit around gathering dust!
#7, DaveChild, United Kingdom, 4 August 2008. Reply to this.
Lazy alternative is to have everything point to index.php except in an assets directory (which contains css and images) and have index.php sort out what to do with the url structure.
This is usually much easier than building a really smart .htaccess that can handle lots of situations.
#8, Robert Kohr, United States, 4 August 2008. Reply to this.
Robert: I'd be interested to know whether it was more efficient to use htaccess than PHP to sort out the URLs. You are quite right that in some situations it can be easier to simply let a single script handle the work.
#9, DaveChild, United Kingdom, 4 August 2008. Reply to this.
Great guide - really meaty! The cheat-sheet has been really useful for ages, and I can imagine this being the perfect companion.
@Robert - I'm sure I once read a way of using PHP as a smart processor for .htaccess, but which didn't resort to just using index.php In fact, I'm pretty certain that this is the technique used by the symfony framework, but don't quote me! :)
#10, Thomas Wright, United Kingdom, 5 August 2008. Reply to this.
Great article! I just discovered url rewriting a few months back and wish I had this article to learn from. Oh well.
FYI, there is a great open source url rewriter for IIS called Ionics Isapi Rewrite Filter or IIRF. By the looks of your article here IIRF does everything ISAPI_rewrite does.
http://www.codeplex.com/IIRF
#11, Peter A, United States, 5 August 2008. Reply to this.
Beginners don't forget http://www.mod-rewrite-wizard.com/
#12, omid, Unknown, 5 August 2008. Reply to this.
I've wanted to use mod_rewrite for a while now, but I discovered they have a drawback that all link references have to be absolute when the url is rewritten.
This is a bit of a turn off for me, as the portability in relative urls is very useful.
#13, Pete B, United Kingdom, 5 August 2008. Reply to this.
good presentation. information rich. useful.
good work
#14, raja, India, 5 August 2008. Reply to this.
Thomas: Thanks. I hope that between them the article and the cheat sheet make a decent resource!
Peter: Nice find. I'll have a look at it. An open source rewriter for IIS would be brilliant if it can do everything ISAPI (or even better, mod_rewrite) can do.
Pete: I don't think that's quite right - almost all of the rules I use here use relative paths. Are you talking about a specific type of rule?
omid, raja: Thanks :)
#15, DaveChild, United Kingdom, 5 August 2008. Reply to this.
Thank you for a lucid and practical article on URL rewriting. Can't tell you how many articles I've pored over, trying to make sense of it with my layperson's eyes.
But I do wish I could print it out. Even selecting all and then trying to print only selection doesn't work. Using FF 3.0.1. Do you think you can offer a printer-friendly page on this article?
#16, Daitya, Malaysia, 5 August 2008. Reply to this.
Daitya: Thanks - glad you like it.
Apologies for the printing issues. I've redone the print style sheet, so it should be absolutely fine now. Let me know if you have any more trouble.
#17, DaveChild, United Kingdom, 5 August 2008. Reply to this.
I havent done anything with url rewriting in years, and then today I had to do some at work. Was about to look for a guide when I noticed this on your RSS feed
Brilliant work Dave, really detailed and made a nice refresher as I havent touched the horrid stuff in so long!
(Monty python quotes cheared up a dragging tuesday afternoon too :) )
#18, Fuzzy Orange, United Kingdom, 5 August 2008. Reply to this.
very informative article on URL re-writing. Completely top-notch content regarding regex, Rule and conceptual information.
My only nitpick is the idea that all these settings go in an .htaccess file. .htaccess files are local settings per on a per directory case. Also since they are loaded on every document request -- they are self defeating if you are simply re-writing to another url when you load that document.
Permanent changes like rewrite rules should go into your site setup (vhost entry or directory entry) within your apache configuration. only if you can't touch the primary configuration files of apache -- should such settings then go into a per-directory local configuration file. Any dev site should use .htaccess to configure/build a site ... a production site should not use htaccess files.
But all in all a very information -- and well informed article on url rewriting.
#19, david g., United States, 5 August 2008. Reply to this.
Hi, Dave, an thanks for a terrific article.
I had a problem with an .htaccess trick a while ago, so I switched it off and hid.
I was just yesterday wiggling my toes in some regex, so I thought might have a crack at the mod_rewrite, and what I?ve tried so far works a treat.
One odd thing, though; I didn?t set up any backreference or forwarding for query strings,
RewriteRule ^something?$ SomethingElse\.php [NC,L]
but an array of requests after a ? seem to get forwarded anyway.
Is something waiting to bite me, I wonder?
Great piece, thanks again.
#20, David, London, 5 August 2008. Reply to this.
Thanks. very useful info.
#21, Sangesh, Unknown, 6 August 2008. Reply to this.
You should consider compiling all these fantastic pieces into books. It would save me the effort of having to bookmark every single post of yours.
#22, Joen, Denmark, 6 August 2008. Reply to this.
good,very good...
#23, gaijun, China, 6 August 2008. Reply to this.
Thanks a lot for this tutorial.
URL rewriting is something I've been very interested in for a while, but could not find a good tutorial on it. This is excellent work, and very much appreciated!
#24, Dan, Canada, 6 August 2008. Reply to this.
This is a phenomenal tutorial. Well done. I will ask our developers to take a look at this!
#25, Simon Slade, Unknown, 8 August 2008. Reply to this.
Thank you for sharing you great skills. This is certainly an excellent tutorial. URL rewriting has always been a topic of interest for me, and this tutorial makes things easier.
#26, Sean, Sweden, 8 August 2008. Reply to this.
Thank you ver much, Dave :-)
Great stuff.
#27, Klaus, Unknown, 9 August 2008. Reply to this.
thanks for this info. I just looking for something like that..
#28, jasmin, Turkey, 11 August 2008. Reply to this.
Thank you for sharing you great skills. This is certainly an excellent tutorial. Please don't stop sharing knowledge. Please go a head.
#29, Allot Jose, India, 12 August 2008. Reply to this.
Fantastic tutorial on rewriting Dave. I think this has to be the most concise tutorial that I have read on mod_rewrite and I have read a few.
Well done mate!!
#30, Rob, Spain, 13 August 2008. Reply to this.
this article is a good start to learn about url rewrite feature. thanks
#31, Mario, Indonesia, 17 August 2008. Reply to this.
A good trick to reduce the complexity of your rewrite file is to use just one argument for all pages, and structure that one argument according to the ordinary rules for an URL.
That's totally unclear, so let me give an example. Instead of writing an URL like this:
http://foo.com/index.php?category=cats&prodID=8
... and then remapping it like this:
RewriteRule ^cats/([0-9]+)/?$ index.php?=category=cats&prodID$1 [NC,L]
... write an URL like this:
http://foo.com/index.php?query=cats/8
... and then remap it like this:
RewriteRule ^
... and remap it like this:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?query=$1 [L,QSA]
The first two rules specify that requests for real existing files or directories should be allowed through. Absolutely everything else is passed to index.php as the "query" argument, whereupon index.php checks a database (or similar) to find out what bit of content that query points at.
By reducing the possible query parameters to just one, you substantially reduce the complexity of the .htaccess file. Of course, doing so increases the amount of work the content management system has to do. So there are trade-offs. I rather like it, though -- doing it this way means I don't have to muck around with the .htaccess file every time I want to add a new category or whatever. I picked up the trick from the .htaccess file that comes with Drupal. I'm rather ambivalent about Drupal as a whole, but they do have quite a lot of nifty tricks.
#32, Will, United States, 19 August 2008. Reply to this.
Hey,
I liked your good post. When I tried to prop your article, I found that 301 status code is issued and hence I couldn't bookmark at propeller.
Would you mind to fix it?
#33, Sri, India, 20 August 2008. Reply to this.
Read the apache 2.0 guide and this and tried both ways
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/(.*) http://www.example.com/$1 [L,R]
and
RewriteCond %{HTTP_HOST} ^example\.com
but this didn't seem to work for many named virtual hosts (many hosts to one ip address)?
Anybody have any experience with that? just seems to redirect to the main domain and not the one i want it too. Would appreciate any help.
Thanks , Bob
#34, coworkerbob, United States, 20 August 2008. Reply to this.
Great...
Very helpful
#35, Dharmendra, India, 23 August 2008. Reply to this.
Great article. You have a small typo on this line with the word identify.
"indicates that the pattern will idenfiy"
#36, Nick, Unknown, 28 August 2008. Reply to this.
Good job on this tutorial. It is definitely one of the best resources for mod_rewrite that I have seen through my travels.
#37, Allen, United States, 29 August 2008. Reply to this.
I was wondering; how about caching? Since your site is using it.. Does this allow the blog is creating a new file each time you change something and/or a comment is added? How about the menu, what if that changes, do all pages get re-created?
#38, Gilles, Netherlands, 2 September 2008. Reply to this.
@Gilles: The page is regenerated when a comment is added. Actually, it's regenerated upon a "POST" request. Cached files expire regularly enough that I'm not fussed about other items changing. Better to have the site up and have a few pages slightly outdated than code for every eventuality in this case.
#39, DaveChild, United Kingdom, 2 September 2008. Reply to this.
very useful examples and great tutorial.
#40, Julia, Spain, 11 September 2008. Reply to this.
yo Great tutorial!Im kinda newbie to mod rewrite so it helped me a lot undestand how this thing work.I have found really nice tool for regex if anyone is interested, check this out:
http://gskinner.com/RegExr/
#41, mokracipka, Ireland, 26 September 2008. Reply to this.
One of the best Rewrite tutorials I found so far :) Congratulations for the nice work.
Favorited and also will recommend to friends.
#42, Alfred R. Baudisch, Brazil, 27 September 2008. Reply to this.
Dave You're the man :D
#43, Janet, Unknown, 28 September 2008. Reply to this.
As expected, excellent reading, Dave.
Thanks, as always...and keep us posted on any I <3 JD rulings. ;)
#44, roto, United States, 1 October 2008. Reply to this.
Nice one !
#45, Deepak, Unknown, 2 October 2008. Reply to this.
what if I don't have access to the code files (we're using a 3rd party for all web coding) and we can't have them re work the way their code files generates hard links on the site.
so, if I want http://domain.com/ViewCart.aspx?somevalues....
to resolve to: http://domain.com/cart
I can easily set a rule allowing http://domain.com/cart to resolve correctly - but that only covers when a visitor enters our site through the clean url.
what if they click on the "view your cart" link - and are taken to:
http://domain.com/ViewCart.aspx?somevalues....
in that case, the browser address bar shows the ugly url, which would let the user share, or link to, or bookmark the ugly url.
is there a method for dealing with this?
#46, fcp, Unknown, 6 October 2008. Reply to this.
You 'da' man!! This article helped me out a lot. Thanks.
#47, Rob, United States, 10 October 2008. Reply to this.
good one, helped me out.
#48, memic, Germany, 13 October 2008. Reply to this.
Nice article. It was very helpful for me.
#49, Doko, Czech Republic, 16 October 2008. Reply to this.
Great guide.
I wonder if you can help with a problem I am having and can't figure out.
I am trying to get a URL like:
/joomla/content/view/137/66/
to
/content/view/137/66/
I currently have joomla installed in the joomla folder and wish to move it to the main directory without ruining the SEO.
#50, James Tombs, United Kingdom, 16 October 2008. Reply to this.
Excellent post, Dave. I'm afraid I don't have anything to add to the discussion as I'm a real newbie at this stuff, but just wanted to say thanks for a really good article.
#51, Rodney Smith, Unknown, 20 October 2008. Reply to this.
Hi Dave, I just discovered this site today and I wish you can help me out with this issue. I have a photo gallery that generates album and image URLs each time an album and/or image is added. The generated album URLs look like this:
index.php?page=list-image&album=1
index.php?page=list-image&album=40
In one of my SQL tables I have an Album Name row as `al_name`
I want URLs like index.php?page=list-image&album=1 to be rewritten by printing out /$row['al_name']
So, the rewritten URL will look similar to /Best_Wedding_Photos/ if the Album Name is: Best Wedding Photos
Similarly, I need your help to rewrite the likes of the URLs below:
index.php?page=image-detail&album=1&image=1
index.php?page=image-detail&album=1&image=2
I would like the likes of the these image URLs to be rewritten as:
/Best_Wedding_Photos/image-1.html if the Album Name is: Best Wedding Photos and image=1
I thank you in advance for your assistance.
#52, Mexabet, Australia, 21 October 2008. Reply to this.
Thanks. You explained very clearly.
#53, pointer, Unknown, 28 October 2008. Reply to this.
hi, what if i want to rewrite negating a pattern, i.e. a word, not a character class. i didnt find any example considering it.
thanks.
#54, khadija, Azerbaijan, 30 October 2008. Reply to this.
Great tutorial! Thanks!!!
#55, Todd Perkins, Unknown, 3 November 2008. Reply to this.
Its the best tutorial I have ever read.
Thx!
regalio/decimus
#56, decimus, Poland, 12 November 2008. Reply to this.
I was looking for windows based mod rewrite and I am glad that I landed up here. Excellent information on url rewriting in easy to understand style. Thanks a lot.
#57, Arun, India, 21 November 2008. Reply to this.
Nice Tutorial
Thanks
#58, MMF, Unknown, 23 November 2008. Reply to this.
I really like this tutorial. it did explain the problem i was having. in your Patterns and Replacements section you show how to make a simple url redirect to a less simple url. example:
site.com/pizza/ to site.com/food.php?type=pizza
i'm kinda looking for the opposite. how would i do that.
#59, Doug, Unknown, 24 November 2008. Reply to this.
Nice tutorial Dave, I am very thankful to you very much.
#60, Ahmad Ginani, Unknown, 27 November 2008. Reply to this.
Browsing for this tutorial for a long time...
This is what I'm looking for ...
Thanks Dave.
#61, Myea Amelia, Indonesia, 28 November 2008. Reply to this.
Thanks a bunch DAVE. This tutorial was of big help.
#62, AJ, Nepal, 9 December 2008. Reply to this.
Early on in the tutorial you show
^pet-care/?$
but in the next paragraph you show
^/pet-care/?$
It seems like it needs that extra slash in there, true?
#63, Andy Roberts, United States, 15 December 2008. Reply to this.
Never thought I'd get my head around mod_rewrite. This article just proved me wrong.
Thanks alot!
#64, Thomas, Australia, 28 December 2008. Reply to this.
hi,
can anybody please tell me how to change :
http://localhost/adde/store/product.jsp?BV_UseBVCookie=Yes&productID=Yes&oID=12
to
http://localhost/adde/store/product.jsp?oID=12&productID=Yes
Most important thing is i need the params in this order regardless of in what order they are in initial url. This is for SEO and
one more question...
it is bit urgent and i tried to find this on net but of no use because in every forum people talk of stripping query string or adding the new parameter but nobody tells how to alter the exisiting query string.
#65, avivesh, United States, 30 December 2008. Reply to this.
Very good guide. Thank you.
#66, Shani elharrar, Unknown, 1 January 2009. Reply to this.
i want to change the first part of my URL like
http://mysite.com
http://bigboss.mysite.com for http://mysite.com?person=bigboss
similarly
http://bigman.mysite.com for http://mysite.com?person=bigman
Thanks in advance for the help
#67, Asim, Australia, 5 January 2009. Reply to this.
Thanks for this. The Apache documentation can be useful but very dry at times. And testing this functionality is always a pain.
#68, Rimian, Australia, 11 January 2009. Reply to this.
Very interesting and useful article.
#69, Pascal, Ukraine, 12 January 2009. Reply to this.
I'm new to php. I need to protect my variable value representing in the url. I think U not get it. Actually I'm retreiving database records by using pagination up to that its fine, but in the url it is displaying entire thing clearly how and form where to where the values are flowing. so I think it becomes very poor code.
so I need information on pretty urls, I accidently visited this site I spend a lot of time, I understood clearly this rewrite method, but I cant get it implement to my application..
So I need some more help with clear steps how to use this rewrite for pretty urls.
Thanks in advance. If any one helps me.
#70, ekshvenu, Unknown, 13 January 2009. Reply to this.
very interesting but need with example for php developers. Mainly me like beginners.
#71, ekshvenu, Unknown, 13 January 2009. Reply to this.
My problem is to change url from
http://localhost/simpleapp/index.php/viewEmp/showData/&per_page=5
to simple format. like it should not display the value atlast .
#72, ekshvenu, Unknown, 13 January 2009. Reply to this.
Pretty thorough tutorial. A quick question though;
What if I wanted the variable to disappear altogether? e.g.
http://www.pets.com/show_a_product.php?product_id=7
shows just http://www.pets.com/product
as opposed to http://www.pets.com/product/7/
Is that possible?
#73, Rollins, Unknown, 20 January 2009. Reply to this.
Thank you for the tutorial. I already knew how to rewrite messy dynamic url to more user and seo friendly url but I wanted to add a second rule for the index pages. Your tutorial help me to get over that hurdle, thanks.
What I wanted to do was rewrite www.example.com/blog/index.php (www.example.com/blog/ also works) to www.example.com/blog/index.html
Here is my solution:
RewriteEngine On
RewriteRule ^index\.html$ /blog/ [NC,L]
#74, Jon Lyles, Montreal, Canada, 1 February 2009. Reply to this.
This is a great article, thanks for sharing it. (The cheat sheet is nice as well)
#75, James, United States, 14 February 2009. Reply to this.
This is amazing information Dave. Thanks for the effort
#76, varun, Unknown, 17 February 2009. Reply to this.
@dave: Thanks for the primer. Can I suggest a part two, which would be the next logical step for me - using mod_rewrite in a cms. Maybe with a flow diagram of cms > url request > front-end template > database > htaccess to help people understand the logic. I've been through a couple of rewrite tutorials, but they are teaching me regex, not architecture. I'm about to start implementing a rewrite in my own cms which will create /auto-descriptive-maxlength-urls/ from article titles and categories, (or manual override if the user wants). I see your url for this article implements this.
@will: #32 I'm there on Drupal - I'm getting a bit jaded with the fragmentation of the admin UI, so I think I'm just going to build this functionality into my own cms rather than use Drupal.
@fcp: #36 I have a similar question -say for example, I want to link through to another article without my user having to open the browser to navigate through to the link. I guess I'd have to use the basic php rewrite class and parse all my links through it. Rather that than try rewrite all the links in the page at runtime...
#77, Murray, Johannesburg, 9 March 2009. Reply to this.
Thank you, great tutorial! Maria
#78, Maria, Unknown, 17 March 2009. Reply to this.
Dave, thanks a lot. I was able to use this fine tutorial to write search-engine-friendly URLs for my blog.
#79, Treats, USA, 19 March 2009. Reply to this.
Cheers Dave, this is great stuff. You have inspired me to start work on Zeus cheat sheet as couldn't find anything that compares to this as a resource.
Regards
James
#80, James, United Kingdom, 25 March 2009. Reply to this.
Thank you. A very good tutorial
#81, Henri, Netherlands, 5 April 2009. Reply to this.
Hi Dave,
Thanks for your tutorial finally i solve my problem , realy great tutorial
Regards
Aditya
#82, Aditya, Indonesia, 13 April 2009. Reply to this.
Awesome Article!
Thanks. It really help me!
#83, Luciano Sampaio, Unknown, 13 April 2009. Reply to this.
thanks a lot really very important article
#84, Ayman R. Hussein, Palestinian Territory, Occupied, 19 April 2009. Reply to this.
Nice articlet and very helpful for beginners.
#85, Arun Janarthanan, Unknown, 1 May 2009. Reply to this.
Very good and helpfull Article.
#86, Barney G., Germany, 5 May 2009. Reply to this.
Great article for beginners
#87, gaurab, kathmandu,nepal, 10 May 2009. Reply to this.
hey hi... im using an .htacces file for having clean urls of the form:
http://www.site.com/file/method/param1/param2/param_n
the htaccess file looks like:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php?rt=$1 [QSA,L]
which i get from a site... and it works well...
The problem is when i do a <form> and in the action property i dont know how to put the addres so the url string stop growing... I mean if i put an action like <form action='page/value'> he will redirect me to http://www.site.com/page/value/page/value and imagine that i made some validations and the person needs to enter data again... (like a login form) then adress would become like http://www.site.com/page/value and it will keep growing...
how can i do to stop that behaviour?
Thanks...
#88, Miguel, Brazil, 12 May 2009. Reply to this.
Great article for beginners
#89, Marco, Spain, 18 May 2009. Reply to this.
Awesome! Your writing style is easy to follow and you incorporate just the right amount of detail to be absorbed as a web article. Thanks for the help.
#90, Morgan Ney, United States, 24 May 2009. Reply to this.
I clicked "I like it" on StumbleUpon thanks to the Monty Python bit :)
#91, John, United Kingdom, 28 May 2009. Reply to this.
I found what I needed. Simple and fluent article. Thank you.
#92, Hasan TOKATLI, Turkey, 31 May 2009. Reply to this.
Amazing Tutorial! Thanks for the great resource. Giving you a thumbs up on stumble!
#93, sam, Unknown, 12 June 2009. Reply to this.
Thank you so much for taking the time to put together this clear tutorial. mod_rewrite is clearer to me than it has ever been and so is the use of regexes. I had some serious wordpress issues that had my blog down for a couple of days and I thank you for helping be get it back up!
#94, diamondTearz, United States, 17 June 2009. Reply to this.
Great article for beginners
#95, Css code, Turkey, 17 June 2009. Reply to this.
PEACE BE UPON U !
article was superb I hate mode_rewriting but from this article I got a very clear idea about rewriting
MASHA ALLAH !!!
:TOW THUMBS UP:
#96, farshad, Srilanka, 27 June 2009. Reply to this.
Thanks so much! This is just what I was looking for.
#97, Shaun Swegman, Dallas Texas, 4 July 2009. Reply to this.
Such a great and useful article. Great resource . Thanks
#98, kamran, Pakistan, 21 July 2009. Reply to this.
Thanks! It's very nice :-)
#99, Jannick, Netherlands, 26 July 2009. Reply to this.
This is so easy to understand, but none of it works on my host. I'm using hostmonster. Aparently I must install CMS like WP, Joomla or Drupal to get it working. Can someone give me the names of a few hosts that allows for these codes to work by directly placing them into the .htaccess file and onto the main directory?
Thanks
#100, Lisa, Antigua And Barbuda, 30 July 2009. Reply to this.
Just wondering why a set of re-write rules, such as:
RewriteRule ^([a-zA-Z0-9]+)/?$ index.php?content=$1
..does not work on hostmonster nor ixhosting accounts but rules like:
RewriteCond %{HTTP_HOST} !^www.domain.com$
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301]
these do. Must something else on the accounts be activated in order to get rules for clean urls to work?
Thanks a lot.
#101, Lisa, Saint Lucia, 3 August 2009. Reply to this.
Great tutorial,i was trying to make regular expression that redirects to my home page if user enters anything after my website name eg.www,mysite.com/sd/as/d234a/d/asda/d/a/d/a/d
if user enters any absurd url it redirects to home page.how can i do that ??
Thanks.
#102, Simer, India, 11 August 2009. Reply to this.
Great post. Rare to find such a great posts. When I begun my search for the information on Rewriting URLs I found exactly everything that wanted to know!
Cheers!
#103, STRGPune, Pune, India, 13 August 2009. Reply to this.
Great resource, having trouble redirecting to hide index.php, with multiple before-and-after words possible. Any chance of a specific rule for that? Thanks!
#104, Molecule, Australia, 19 August 2009. Reply to this.
That is the clearest tutorial for rewriting. Thank you indeed.
#105, Kerem, Turkey, 20 August 2009. Reply to this.
your tutorial is great! now i am understand how to rewrite the URL to make it search engine friendly.. :D
bookmarked. :)
#106, OOnly, Unknown, 16 September 2009. Reply to this.
it doesnt work for me.. im using apache 2.2.4. it does have mod_rewrite.
it doesn't redirect to the page...
i just copied and replace it with my url..
im not sure where to put the .htaccess. i just put it to the root folder. it just doesn't work...
help please...
tahnks!
#107, angelo rodelas, philippiness, 18 September 2009. Reply to this.
i found what my problem is... ive reconfigured my httpd.conf file of apache...
thanks for the this tutorial. i wll bookmark this and for sure it will help me so much. im doing web-based application using JSP used internally.
thanks alot.. ive learned something new...
#108, angelo rodelas, philippiness, 18 September 2009. Reply to this.
Great article. This is a reference for us. Testament to its quality is that is from over a year ago and still gets new comments and is linked from many places. Great job!
#109, Mario Canamar, Canada, 19 September 2009. Reply to this.
Although Google claim to not like re-written urls I feel that this is just part of the way that we hake a website user friendly. Personally I am all for them, i tend to work with the ISAPI mod and think it is great, one tip is always be aware of duplication issues from accessing the same page via 2 urls.
#110, Birmingham Jon, United Kingdom, 26 September 2009. Reply to this.
At long last I finally conquered mod rewrite voodoos (well atleast everything that I need). Thanks Dave you look great!
#111, Stone Deft, Unknown, 2 October 2009. Reply to this.
@Birmingham Jon -"Although Google claim to not like re-written urls " Does this mean when you re-write your URLs google wouldn't like it?
#112, Stone Deft, Unknown, 2 October 2009. Reply to this.
Helpful tips for beginners like me.
#113, PHP Gallery, Australia, 14 October 2009. Reply to this.
^ agreed.
I always read this article when I forget what [NC,L,QSA] means =))
#114, iwanttobelieve, Viet Nam, 15 October 2009. Reply to this.
I recommend RegexBuddy (www.regexbuddy.com) to anyone who works with Regular Expressions, it's an excellent utility! Even though I'm quite fluent with RegEx, I find it very useful, especially when working with more complex RegEx.
(I'm in no way associated with JGSoft ? just a satisfied customer :-)
#115, Ville Walveranta, Texas, USA, 17 October 2009. Reply to this.
Dave, thanks for the info really helped me alot
#116, ????? ????, Israel, 21 October 2009. Reply to this.
Thanks a lot Dave for writing such a wonderful tutorial?truly useful
#117, Hardik, India, 26 October 2009. Reply to this.
Thank you so much Dave! nice article...
#118, Azam, Australia, 28 October 2009. Reply to this.
Does this mean its better to use a dash character"-" rather than a underslash character "_" on urls.
#119, Offshore Seedbox, Unknown, 31 October 2009. Reply to this.
Really useful information. God bless for putting up the topic in the simplest manner.
#120, victor.gurung, bhutan, 31 October 2009. Reply to this.
that is really useful topic for begginners
thanx alots
#121, rahul, Unknown, 3 November 2009. Reply to this.
Dave, thanks for the info really helped me alot
#122, vijay, hyderabad, 12 November 2009. Reply to this.
Amazing article thanks. But there a not only information for beginners ;-) My project http://www.tweet-rank.de uses up to 20 different rewritings.
#123, David, Germany, 16 January 2010. Reply to this.
Hi Rob, just came across this article and have really enjoyed reading it - basically its's a clear and concise tutorial!
#124, spain seo, spain, 25 March 2010. Reply to this.
i got good information about url rewrite.i learnt some thing.
thanks
#125, kashif, pakistan, 20 April 2010. Reply to this.
I was looking for this, some htaccess of mine are not working properly, thanks Dave
#126, Musicboot, 29 April 2010. Reply to this.
Dude seriously, it's more than I came looking for
@#119: Since underscore is a word character, search engines won't consider words divided by underscore to be separate words, better to use hyphen I guess
#127, games freak, india, 5 May 2010. Reply to this.
Well, it is a very informative post and it is very useful especially for those who are very new in the web designing and web development and it's also very important according to SEO point of view and the basic purpose of the URL rewriting is to make your site more and more search engine friendly so that the search engine can easily crawl it...
#128, Internet Marketing Services, USA, 8 June 2010. Reply to this.
Brilliant atricle !!!
#129, Velu, UK, 7 July 2010. Reply to this.
Very useful information on this article..Thanks for sharing.
#130, Website design chennai, India, 13 July 2010. Reply to this.
Nice article, figured out how to go from 'pretty' URL's to 'ugly' ones for processing, but still want the URL to stay pretty. Any way to do this? Thanks!
#131, David Lefkon, USA, 21 July 2010. Reply to this.
Best and most helpful article covering the area of url rewriting i found so far. The guide provided by Apache and linked to above might be more detailed, but is very hard to understand for a beginner.
#132, Alex, Germany, 31 July 2010. Reply to this.
Maybe im just retarted but I read threw this about 30 times and I still cant get this problem i have...maybe some1 can help???
I have this url
http://whatever.com/hello/123_4.html
I would like to rename that file using a rewrite rule(i guess) to the following:
http://whatever.com/hello/somethingelse.html
Any help would be greatly appreciated..Thanks!!
#133, John, US, 9 August 2010. Reply to this.
Finally a tutorial for us dummies!!!!
Thanks!
#134, Eleven, 20 August 2010. Reply to this.
Hi everyone!
its a terrific tutorial! Thanks!
And I tried to use a similar rewrite to yours:
RewriteRule ^parrots/([A-Za-z0-9-]+)/?$ get_product_by_name.php?product_name=$1 [NC,L]
but it is just working with the [R] flag:
^kategorien/?(.*)_([0-9]+)\.html$ kategorien.php?catItem=$2 [R,NC,L]
but I dont like to use it in that way, because i am losing the nice seo path in the browser url adress field:
http://localhost/projcetname/kategorien/fussball/fussballschuhe/hallenschuhe_203.html
Why do I have that problem and what can I improve?
Thats so much for your help!
#135, jeremy, Germany and Canada, 22 August 2010. Reply to this.
Great documentation. Very useful. Thanks for your time
#136, Hari, India, 6 September 2010. Reply to this.
Hi
I using XAMPP Apache server. I have enabled mod_rewrite. But url rewriting not working. Please help me.
in .htaccess
RewriteEngine on
RewriteRule ^view/([0-9]+)/?$ view.php?id=$1 [NC,L]
URL: http://localhost/Wonderingfacts/view.php?id=1
Please help me...
Regards,
Seeni
Replies: #140.
#137, Seeni, India, 16 September 2010. Reply to this.
Great article, best I’ve found on URL Rewriting, very helpful, just tweeted it!
#138, Just Web Design, UK, 21 September 2010. Reply to this.
my httaccess:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^member/([A-Za-z0-9-]+)/?$ direktori2.php?Store=$1 [NC,L]
</IfModule>
* PT-BRAMA-EXPRESINDO-Transportasi&Ekspedisi = store
my link : http://localhost/abelputra/member/PT-BRAMA-EXPRESINDO-Transportasi&Ekspedisi
why this error 404?
but if my link : http://localhost/abelputra/member/PT-BRAMA-EXPRESINDO-Transportasi-Ekspedisi
OK
the problem is any character "&" in store
thanks
#139, Irwan, Indonesia, 8 October 2010. Reply to this.
#137 @seeni Unless you write a redirect script, http://localhost/Wonderingfacts/view.php?id=1 will always look just like that. Your URL should look like this: http://localhost/Wonderingfacts/view/1 . Then, silently, Apache rewrites it on the server and sends the "correct" URL to your scripts...
#140, Tieson Trowbridge, US, 3 November 2010. Reply to this.
Its a great tutorial that I was looking for. I've used this .htaccess tips for rewrite my rss url using this:
RewriteRule ^rss.xml$ rss.php [NC,L] # Change feed URL
Thanks AddedBytes :)
#141, alfamp3, Indonesia, 7 November 2010. Reply to this.
Really great tutorial, many many thanks :)
Would it be too much to ask for a PDF version of this article?
Thanks in advance.
#142, John Z, 9 November 2010. Reply to this.
Can somebody please give an example of a rewrite rule based on the below URL:
old url:
http://www.MySite.com/scripts/prodList.asp?idCategory=22
New url:
http://www.MySite.com/5-new-new
Many thanks
#143, probashi, uk, 17 November 2010. Reply to this.
Quick question: I'm trying to use the basic rewrite rules, following your tutorial:
RewriteEngine On
RewriteRule ^test/?$ index.html [NC,L]
this should mean that webroot/test/ should show webroot/index.html right? 'Cause it doesn't work at my localhost (XAMPP for Windows). I feel like I'm missing something, so.. please help? :) I've done a few hours of googling and I can't get it to work!
#144, Ruubje, Netherlands, 18 November 2010. Reply to this.
Nice easy to follow article. This combined with your cheat sheet has helped me a ton. Thanks Dave.
#145, Anthony, 18 November 2010. Reply to this.
Thank so much for this....
it's really helpfull............
keep up 8th the good job
#146, diokey, 19 November 2010. Reply to this.
Google it!!!
#147, CheRish, China, 20 November 2010. Reply to this.
A fantastic article!!! I would really like to find out about url rewriting in apache, and I found this article. Thank the author very much for posting it.
#148, Nhan, Viet Nam, 11 December 2010. Reply to this.
Fantastic article. now i am no more a beginner...
#149, zamaan, sri lanka, 25 December 2010. Reply to this.
Hi,
I have started using drupal on lighttpd for the few days.. My directory set up goes like this .
1./document-root/site
2./document-root/site/subsite1
3./document-root/site/subsite2
I am able to get the clean urls for the above sites using lua scripts. I have no problem on accessing the pages using both apache and lighttpd
But I got another site,like
4./document-root/site/subsite3/subsite3.1
When I click the pages on the subsite3 and subsite3.1 I am getting page not found errors when I use lighttpd. but it works fine with apache2. I need help on this.
Thanks in advance...
#150, karthick, India, 27 December 2010. Reply to this.
Thanks, I was having troubles with 301 redirect, and found on your site that I should use the absolute url and it worked. Cheers.
#151, --, United States, 2 February 2011. Reply to this.
I want ti use feature of urlrewriting in my project.
I have added jar urlrewrite-3.2.0.jar in my WEB-INF/lib directory. and also added WEB-INF/conf/urlrewrite.xml file .
I have set rules as follows <urlrewrite>
<rule>
<from>^/package/([0-9]+)$</from>
<to>viewpackagedeal.do?dealid=$1</to>
</rule>
<outbound-rule>
<from>^viewpackagedeal.do?dealid=([0-9]+)$</from>
<to >/package/$1</to>
</outbound-rule>
and in my JSP file I have link
<a href="viewpackagedeal.do?dealid=995" target="_blank">
I even triend doing <a href=<%response.encodeURL("viewpackagedeal.do?dealid=995")%> target="_blank"> still the it doesnot work ...
please help me ..I am going wrong some where ?
#152, Varsha Gaonkar, India, 7 February 2011. Reply to this.
A W E S O M E tutorial for beginners !!
thanks a lot for this !!!
#153, --, india, 6 March 2011. Reply to this.
Thanks for providing valuable info on url rewriting. I have a query on this. I want to redirect a application URL (which is deployed in Microsoft IIS Server) to a Gateway URL. I dont want to display the application URL. Instead, want to use my Gateway URL as we have integrated the webapplication with the Gasyeway. Is this possible with the above configurations? Anypointers on this is appreciated.
#154, Srikanth, India, 7 March 2011. Reply to this.
Hello,Nice Tutorial
Can you tell me in detaile ,I want my site redirect from www.mysite.com/production to www.mysite.com. What is rewrite rule in both .htaccess file for that.Mens for root folder & subfolder production .
Please help me out
#155, Dice, India, 11 March 2011. Reply to this.
And one think I forget to tell you is I m using friendly url & its working properly
#156, Dice, India, 11 March 2011. Reply to this.
bleary eyed and stuck!
I can't seem to get my syntax correct. I would like to have all requests destined for google.com be sent to our internal webserver which I am doing via a bogus DNs entry returning our webservers public ip. Once at our webserver I need to rewrite urls to replace the query string portion that says &safe=off or uss=1
After the substitution has taken place I want to Proxy the request out to the real google on behalf of out user, and then return the results to them.
Our webserver hosts no sites I setup a vanilla apache instance, and if you can recommend different I am happy to follow your wisdom
The two query string elements are used to disable moderate browsing settings, and prevent Porn from coming up. Hence the desire to add &safe=strict or safe=on back in.
When I try to do it though my logic, the new values are being placed before the initial ?, so i end up with something like: www.google.com/imagessafe=strict?blah , or i get www.google.com/images&safe=strict?blah
am i running into this because these rewriterules expect that they are rewritiing things that should be on the local filesystem vs out in the cloud somewhere?
any help is appreciated, ive probably stared at this for two weeks now :) Below are some various examples of what I have tried please ignore the [R] that was just a failed testing attempt, I really prefer a proxy solution. Caching is not needed. I'm just hopelessy lost and in need of coffee
--
RewriteRule /(.*)$ /images?safe=strict&sub_id=$1 [QSA,P]
RewriteRule (.*)safe=off(.*)$ /$1safe=active$2 [QSA,P]
RewriteRule (.*)\?(.*)uss=1(.*)$ http://cnn.com/ [R]
#157, ron, 14 April 2011. Reply to this.
Definitely the most clear and simple tutorial for this, had to plough through heaps of useless ones before I found this gem!
#158, Chris, Scotland, 15 April 2011. Reply to this.
I tried to rewrite the URL :
http://www.foo.php/page.php?artical=1&topic=4
to
http://www.foo.php/page/1/4/
my rule is
RewriteRule ^page/([^/]*)/([^/]*)/?$ /page.php?artical=$1&topic=$2 [QSA,L,NC]
is working
but when i click to another link it concatenate the previous url and become
http://www.foo.php/page/1/4//page/1/15/
Everything is dynamic and coming from MySQL database.
Any idea?
Thank you
#159, Jesh, Canada, 17 May 2011. Reply to this.
there is a minor typo in your text.
http://www.pets.com/pet_care_info_07_07_2008.php
should be
http://www.pets.com/pet_care_info_07_07_2003.php
so that is 2003 and not 2008
First part of the tutorial right under the heading
"Basic URL Rewriting"
#160, Godzilla, northpole, 27 June 2011. Reply to this.
I have one pages in my ASP.NET application. I am trying to implement User Fiendly URL using IIS URL ReWrite 2. But I am facing some issues.
category.aspx
original url - http://www.indiafashiononline.com/category.aspx?CCode=womens-wear
user friendly url - http://www.indiafashiononline.com/category/womens-wear
and please see the script given below,
<rules>
<clear />
<rule name="RedirectUserFriendlyURL1" stopProcessing="true">
<match url="^category\.aspx$" />
<conditions>
<add input="{REQUEST_METHOD}" pattern="^POST$" negate="true" />
<add input="{QUERY_STRING}" pattern="^CCode=([^=&]+)$" />
</conditions>
<action type="Redirect" url="category/{C:1}" appendQueryString="false" />
</rule>
<rule name="RewriteUserFriendlyURL1" stopProcessing="true">
<match url="^category/([^/]+)/?$" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="category.aspx?CCode={R:1}" />
</rule>
</rules>
<outboundRules>
<rule name="OutboundRewriteUserFriendlyURL1" preCondition="ResponseIsHtml1">
<match filterByTags="A, Form, Img" pattern="^(.*/)category\.aspx\?CCode=([^=&]+)$" />
<action type="Rewrite" value="{R:1}category/{R:2}/" />
</rule>
<preConditions>
<preCondition name="ResponseIsHtml1">
<add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
</preCondition>
</preConditions>
</outboundRules>
</rewrite>
But I am facing issues
Step 1.
When I place the mouse over WOMENS WEAR on top navigbar on my site (http://www.indiafashiononline.com), in status bar I can see the link as given below, if I click the link , its working fine and I am getting the url like http://www.indiafashiononline.com/category/womens-wear
status bar - http://www.indiafashiononline.com/category.aspx?CCode=womens-wear
Step 2.
but once I click the link, after that I place the mouse over the same WOMENS WEAR link, the status bar link will change as given below
status bar - http://www.indiafashiononline.com/category/category.aspx?CCode=womens-wear
and I am getting error when I click the same url.
That means the word 'category' in the previous url repeating next time.
means the string '/category' also added with 'www.indiafashiononline.com'. I think the situation is clear to you, Do you think it is because of some mistakes in OUTBOUND RULES ? All the link I have given are live, so that you can try with it. Please go through these and kindly help me to resove this issue.
#161, Ajo Joseph, 29 June 2011. Reply to this.
i have created rule for following url
http://www.amg.biz/garavigujarat as below
RewriteEngine On
RewriteBase /
DirectoryIndex index.php default.php Default.php
RewriteCond %{QUERY_STRING} ^(.*)
RewriteRule ^garavigujarat$ http://www.amg.biz/index.php?page=Publications&id=2
but instead of showing original url it's showing new url. so i think it's redirecting instead of rewriting url.
can you please help me.
#162, kamlesh, india, 6 July 2011. Reply to this.
Great article. New to the mod_rewrite, but thinking it can be used for our goal. We are changing our company name (say from ABC to XZY) and need to have the URL reflect this now - so every page that starts with www.abc.com/some_page will now display www.xyz.com/some_page.
We use Oracle Application Server Portal, and even though through the DNS we can go to www.xyz.com, the Single Sign On redirects to i.e. login.abc.com.
Will mod_rewrite let us keep our internal structure and simply display the new company name in all of the URL pages? Thanks...
#163, Gary, USA, 20 July 2011. Reply to this.
Thanks for all of the tips on url. It's very detailed and good for beginners like me. I was wondering if you had a good xml to pdf converter that you could suggest? Thanks.
#164, Roy Slater, 28 July 2011. Reply to this.
Very great article about mod_rewrite, thanks very much.
my website is made by phpbb, and i will try to rewrite by myself, thank you again.
#165, --, USA, 1 August 2011. Reply to this.
really great article! I special do like the part with multiple rules! but one question i do still have. Is it bad or not to use rules like this
RewriteRule ^(.*)-(6)-([0-9]+)/$ some.php [NC]
RewriteRule ^(.*)-(6)-([0-9]+)/&utm_source=(.*)$ some.php [NC]
#166, Viktor Dite, Deutschland, 4 August 2011. Reply to this.
Good tutorial...
All seems to be "real"...
But...
It doesnt seems to work on my sites...[on all of them -> this is because Im worry about]...
But I see so many sites that has this powerful kind of resources...
Thanks anyway!
#167, DiegoV, Argentina, 13 August 2011. Reply to this.
Hey, I've got a similar article about URL rewriting in C#.NET. Feel free to tell me what you think.
I like your blog structure. It's very straight forward for learning. How long have you been doing this?
http://thecodebug.com/?p=363
Aleks
#168, Aleksandra Czajka, United States, 18 August 2011. Reply to this.
very nice tutorial and very useful for all.
please keep posting article like this.
Thanks
#169, Manoj Kumar, India, 19 August 2011. Reply to this.
Hi everyone,
I've a few problem
- I lost images path, css, js when i using multi level rewrite url.
- When I delete condition in .htaccess, I'm still rewrite url. Why ?
How to solve this problem
Thanks
#170, dido, thailand, 21 August 2011. Reply to this.
very good and very simplified the most effective easy to learn written by experienced person..i love this tutorial
#171, amanjeet singh, india, 26 August 2011. Reply to this.
Good work!!! It really helps me in URL Rewriting..Thanks Man :)
#172, Waqas Mehmood, Pakistan, 8 September 2011. Reply to this.
Hi all,
I have a domain (gayongmaarifat.com) that I need to point at another domain (gayongmaarifagroup.com/pssgmm) where my joomla website installed. which .htaccess I should edit in order to do this and how to hide the real address ?
#173, Razil, Malaysia, 11 September 2011. Reply to this.
Thank you for this article. It helped me a lot.
Cla.
#174, claudio, italy, 14 September 2011. Reply to this.
May be a silly question but when you redirect
http://www.pets.com/show_a_product.php?product_id=7
To
http://www.pets.com/products/7/
The form in show_a_product.php is expecting a product_id
Also there is no page on the server called
products/7/
What am I missing?
Thanks
#175, benny, 30 September 2011. Reply to this.
I just knew what [NC,L] means. The flags section on your article does really help. Thanks
#176, Songhood, 2 October 2011. Reply to this.
Dave, thank you for taking the time to put this together! I've been looking around for info on this topic and your presentation is stellar!
I'm still reading through everything, but I did wonder about something so I thought I'd comment now...
In the example:
RewriteRule ^[A-Za-z-]+/([A-Za-z0-9-]+)/?$ get_product_by_name.php?product_name=$1 [NC,L] # Process all products
the product_name should come from ([A-Za-z0-9-]+) in the source URL - the second group - so shouldn't it be product_name=$2?
---------
I can't wait to finish up reading through this tutorial Dave. VERY well done!
#177, Scott Natter, USA, 11 October 2011. Reply to this.
Thanks Dave; you post will guide me in a right direction.
#178, harikrishna, India, 12 October 2011. Reply to this.
how to rewrite like
(anything).example.com/(anything) to example.com/(anything)
for example :
img1.example.com/test1.jpg to example.com/test1.jpg
img105.example.com/anotherimage.png to example.com/anotherimage.png
tdr.example.com/a.css to example.com/a.css
#179, Biswarup Adhikari, 15 October 2011. Reply to this.
hi when i click on the link it merge in the address bar..
eg...
i click on the home button my link like : http://localhost/test/home/1
now when i click on the another link like contact button my address bar gives the url like : : http://localhost/test/home/contact/2
please any solution for this problem ?
#180, jiya, india, 1 November 2011. Reply to this.
Thank you for a great tutorial
#181, J.K., USA, 1 November 2011. Reply to this.
Hi Dave,
I have a issue.
We can only make a shorter and clean URL by doing all above tutorial. If I want to make url to show the product name, how do I do it?
Example:
When we click on the product on the webpage it show the product description but URL will be like http://192.168.1.170/index.php?option=com_tienda&view=products&task=view&id=19&filter_category=12&Itemid=57
I want to make product name in the url. If I search click on 'Diapers' on our site it will show all products and I can make url like http://192.168.1.170/diapers/
but when I click on one product in the diapers list it should like http://192.168.1.170/diapers/'product name'.
How do I use id as product name in the URL? Please help me.
Your tutorial was just superb!
---
Ravi
#182, Ravi, India, 10 November 2011. Reply to this.
Hi Dave
I have URL
http://www.auto112.eu/pregled.php?id_klijenta=19
http://www.auto112.eu/pregled.php?id_klijenta=20
http://www.auto112.eu/pregled.php?id_klijenta=21
http://www.auto112.eu/pregled.php?id_klijenta=22
and so on.
I have created new fileld in table "short_name" I want to take instead of ...pregled.php?id_klijenta=19
eeg. http://www.auto112.eu/osterman and so on.
Osterman is written in that field.
Is is possible to make one mod write rule that will automaticly take valute from "short_name" field.
#183, Autoservis, Croatia, 16 November 2011. Reply to this.
Well what can I say...
nice tutorial, right, but of no value because things don't work that way!
which makes it really difficult these days with millions of online tutorials ... who do you believe? who is writing them? I get the feeling there are a lot of "want-to-be" or "self-proclaimed" experts out there and - with the internet on their hands, every mouse can be an elephant.
;-)
#184, Heather, Australia, 22 November 2011. Reply to this.
Great tutorial
so helpfull
#185, phpstudent, pakistan, 23 November 2011. Reply to this.
Hi Dave,
I just wanted to thank you very much for this helpful, easy-to-follow, and comprehensive tutorial.
I'll start prettying up my single-page php based web site which has a lot of query parameters to display sections.
Thanks again,
#186, Assem, Jordan, 24 November 2011. Reply to this.
nice artice
#187, bibin(bjp), 26 November 2011. Reply to this.
I had been struggling to find this document for a long time. I think this is a must read for URL rewriting and SEO.
This must be the wikipedia document of URL rewriting. Thank you very much for such a good article.
#188, Gyanesh Sharma, India, 30 November 2011. Reply to this.
Hi, I've been having a problem with mod_rewrite.
here's what i had:
Rewriterule ^admin$ admin/index.php
but for some reason It hasn't been working.
I know that the mod_rewrite rule is working, because I have other mod_rewrite rules in the same file that work fine, it's just this one.
#189, Jesse, 7 December 2011. Reply to this.
The best tutorial i've seen on rewriting.
Thanks a million.
#190, Arend, 14 December 2011. Reply to this.
Good tutorial! Great job. Thanks!!!
#191, Hector, Spain, 27 December 2011. Reply to this.
Thank's,
I am reading this in 2012 and still is the best one !
#192, Aleksandar, Serbia, 9 January 2012. Reply to this.
Thanks and again thanks
Great article!
The best tutorial i've seen on rewriting.
#193, Azfar, Pakistan, 10 January 2012. Reply to this.
I am trying to give each MOVIE there own url name, for example, www.helloworld.com/BATMAN. I have been using mod_rewrite to create such url. I have been using following htaccess code to achieve such result.
RewriteEngine ON
RewriteCond %(REQUEST_FILENAME) !-d
RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-l
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
The mod_rewrite works perfectly. When A user enters randam movie name (name that does not exist in database), for example, www.helloworld.com/abcd, I have created a url redirect which is www.helloworld.com/oopsmovienotfound.php. This works fine too. But the problem I am having is this: When user click www.helloworld.com/login.php .The url keeps looping between login.php and oopsmovienotfound.php OR the url is forwarded to www.helloworld.com/oopsmovienotfound.php beacause database doesnot have "login.php" as a movie name. I thought this command
RewriteCond %(REQUEST_FILENAME) !-f
should have take care of this but its not. Please help. Thank you in advance.
#194, Sam, usa, 17 January 2012. Reply to this.
thanks for your great post , but how to avoid css,js and images dir to be reWriten
thanks
#195, ahmad, Egypt, 17 January 2012. Reply to this.
This is the most comprehensive article that I have come across so far with regard to URL rewriting. thanks!!
#196, Jorge, United States, 29 January 2012. Reply to this.