more .htaccess tips and tricks..

<ifModule>
more clever stuff here
</ifModule>
 

redirecting and rewriting

"The great thing about mod_rewrite is it gives you all the configurability and flexibility of Sendmail. The downside to mod_rewrite is that it gives you all the configurability and flexibility of Sendmail."

- Brian Behlendorf, Apache Group
 

One of the more powerful tricks of the .htaccess hacker is the ability to rewrite URLs. This enables us to do some mighty manipulations on our links; useful stuff like transforming very long URL's into short, cute URLs, transforming dynamic ?generated=page&URL's into /friendly/flat/links, redirect missing pages, preventing hot-linking, performing automatic language translation, and much, much more.

Make no mistake, mod_rewrite is complex. This isn't the subject for a quick bite-size tech-snack, probably not even a week-end crash-course, I've seen guys pull off some real cute stuff with mod_rewrite, but with kudos-hat tipped firmly towards that bastard operator from hell, Ralf S. Engelschall, author of the magic module itself, I have to admit that a great deal of it still seems so much voodoo to me.

The way that rules can work one minute and then seem not to the next, how browser and other in-between network caches interact with rules and testing rules is often baffling, maddening. When I feel the need to bend my mind completely out of shape, I mess around with mod_rewrite!

After all this, it does work, and while I'm not planning on taking that week-end crash-course any time soon, I have picked up a few wee tricks myself, messing around with webservers and web sites, this place..

The plan here is to just drop some neat stuff, examples, things that have proven useful, and work on a variety of server setups; there are apache's all over my LAN, I keep coming across old .htaccess files stuffed with past rewriting experiments that either worked; and I add them to my list, or failed dismally; and I'm surprised that more often these days, I can see exactly why!

Very little here is my own invention. Even the bits I figured out myself were already well documented, I just hadn't understood the documents, or couldn't find them. Sometimes, just looking at the same thing from a different angle can make all the difference, so perhaps this humble stab at URL Rewriting might be of some use. I'm writing it for me, of course. but I do get some credit for this..

# time to get dynamic, see..
RewriteRule ^(.*)\.htm $1.php
 

beginning rewriting..

Whenever you use mod_rewrite (the part of apache that does all this magic), you need to do..


..before any ReWrite rules. note: +FollowSymLinks must be enabled for any rules to work, this is a security requirement of the rewrite engine. Normally it's enabled in the root and you shouldn't have to add it, but it doesn't hurt to do so, and I'll insert it into all the examples on this page, just in case*.

The next line simply switches on the rewrite engine for that folder. if this directive is in you main .htaccess file, then the ReWrite engine is theoretically enabled for your entire site, but it's wise to always add that line before you write any redirections, anywhere.

* Although highly unlikely, your host may have +FollowSymLinks enabled at the root level, yet disallow its addition in .htaccess; in which case, adding +FollowSymLinks will break your setup (probably a 500 error), so just remove it, and your rules should work fine.

Important: While some of the directives on this page may appear split onto two lines, in your .htaccess file, they must exist completely on one line. If you drag-select and copy the directives on this page, they should paste just fine into any text editor.
 

simple rewriting

Simply put, Apache scans all incoming URL requests, checks for matches in our .htaccess file and rewrites those matching URLs to whatever we specify. something like this..

all requests to whatever.htm will be sent to whatever.php:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\.htm$ $1.php [NC]

Handy for anyone updating a site from static htm (you could use .html, or .htm(.*), .htm?, etc) to dynamic php pages; requests to the old pages are automatically rewritten to our new urls. no one notices a thing, visitors and search engines can access your content either way. leave the rule in; as an added bonus, this enables us to easily split php code and its included html structures into two separate files, a nice idea; makes editing and updating a breeze. The [NC] part at the end means "No Case", or "case-insensitive", but we'll get to the switches later.

Folks can link to whatever.htm or whatever.php, but they always get whatever.php in their browser, and this works even if whatever.htm doesn't exist! but I'm straying..

As it stands, it's a bit tricky; folks will still have whatever.htm in their browser address bar, and will still keep bookmarking your old .htm URL's. Search engines, too, will keep on indexing your links as .htm, some have even argued that serving up the same content from two different places could have you penalized by the search engines. This may or not bother you, but if it does, mod_rewrite can do some more magic..

this will do a "real" http redirection:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.+)\.htm$ http://corz.org/$1.php [R=301,NC]

This time we instruct mod_rewrite to send a proper HTTP "permanently moved" redirection, aka; "301". Now, instead of just redirecting on-the-fly, the user's browser is physically redirected to a new URL, and whatever.php appears in their browser's address bar, and search engines and other spidering entities will automatically update their links to the .php versions; everyone wins. and you can take your time with the updating, too.

For details of the many 30* response codes you can send, see here.
 

not-so-simple rewriting ... flat links and more

You may have noticed, the above examples use regular expression to match variables. What that simply means is.. match the part inside (.+) and use it to construct "$1" in the new URL. In other words, (.+) = $1 you could have multiple (.+) parts and for each, mod_rewrite automatically creates a matching $1, $2, $3, etc, in your target (aka. 'substitution') URL. This facility enables us to do all sorts of tricks, and the most common of those, is the creation of "flat links"..

Even a cute short link like http://mysite/grab?file=my.zip is too ugly for some people, and nothing less than a true old-school solid domain/path/flat/link will do. Fortunately, mod_rewrite makes it easy to convert URLs with query strings and multiple variables into exactly this, something like..

a more complex rewrite rule:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^files/([^/]+)/([^/]+).zip /download.php?section=$1&file=$2 [NC]

would allow you to present this link as..

  http://mysite/files/games/hoopy.zip

and in the background have that transparently translated, server-side, to..

  http://mysite/download.php?section=games&file=hoopy

which some script could process. You see, many search engines simply don't follow our ?generated=links, so if you create generating pages, this is useful. However, it's only the dumb search engines that can't handle these kinds of links; we have to ask ourselves.. do we really want to be listed by the dumb search engines? Google will handle a good few parameters in your URL without any problems, and the (hungry hungry) msn-bot stops at nothing to get that page, sometimes again and again and again…

I personally feel it's the search engines that should strive to keep up with modern web technologies, in other words; we shouldn't have to dumb-down for them. But that's just my opinion. Many users will prefer /files/games/hoopy.zip to /download.php?section=games&file=hoopy but I don't mind either way. As someone pointed out to me recently, presenting links as standard/flat/paths means you're less likely to get folks doing typos in typed URL's, so something like..

an even more complex rewrite rule:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^blog/([0-9]+)-([a-z]+) http://corz.org/blog/index.php?archive=$1-$2 [NC]

would be a neat trick, enabling anyone to access my blog archives by doing..

 http://corz.org/blog/2003-nov

in their browser, and have it automagically transformed server-side into..

 http://corz.org/blog/index.php?archive=2003-nov

which corzblog would understand. It's easy to see that with a little imagination, and a basic understanding of posix regular expression, you can perform some highly cool URL manipulations.

Here's the very basics of regexp (expanded from the apache mod_rewrite documentation)..
 

Escaping:

\char escape that particular char

    For instance to specify special characters.. [].()\ etc.

Text:

.             Any single character  (on its own = the entire URI)
[chars]       Character class: One of following chars
[^chars]      Character class: None of following chars
text1|text2   Alternative: text1 or text2 (i.e. "or")

    e.g. [^/] matches any character except /
         (foo|bar)\.html matches foo.html and bar.html

Quantifiers:

? 0 or 1 of the preceding text
* 0 or N of the preceding text  (hungry)
+ 1 or N of the preceding text

    e.g. (.+)\.html? matches foo.htm and foo.html
         (foo)?bar\.html matches bar.html and foobar.html

Grouping:

(text)  Grouping of text

    Either to set the borders of an alternative or
    for making backreferences where the nth group can 
    be used on the target of a RewriteRule with $n

	e.g.  ^(.*)\.html foo.php?bar=$1

Anchors:

^    Start of line anchor
$    End   of line anchor

    An anchor explicitly states that the character right next to it MUST 
    be either the very first character ("^"), or the very last character ("$")
    of the URI string to match against the pattern, e.g.. 
	
	^foo(.*) matches foo and foobar but not eggfoo
	(.*)l$ matches fool and cool, but not foo
 

shortening URLs

One common use of mod_rewrite is to shorten URL's. Shorter URL's are easier to remember and, of course, easier to type. An example..

beware the regular expression:
Options +FollowSymlinks
RewriteEngine On
RewriteRule ^grab(.*) /public/files/download/download.php$1

this rule would transform this user's URL..

  http://mysite/grab?file=my.zip

server-side, into..

  http://mysite/public/files/download/download.php?file=my.zip

which is a wee trick I use for my distro machine, among other things. everyone likes short URL's, and so will you; using this technique, you can move /public/files/download/ to anywhere else in your site, and all the old links still work fine; simply alter your .htaccess file to reflect the new location. edit one line, done - nice - means even when stuff is way deep in your site you can have cool links like this.. and this; links which are not only short, but flat..
 

capturing variables

Slapping (.*) onto the end of the request part of a ReWriteRule is just fine when using a simple $_GET variable, but sometimes you want to do trickier things, like capturing particular variables and converting them into other variables in the target URL. Or something else..

When capturing variables, the first thing you need to know about, is the [QSA] flag, which simply tags all the original variables back onto the end of the target url. This may be all you need. The second thing, is %{QUERY_STRING}, an Apache server string we can capture variables from, using simple RewriteCond (aka. conditional ) statements.

In the following example, the RewriteCond statement checks that the query string has the foo variable set, and captures its value while it's there. In other words, only requests for grab that have the foo variable set, will be rewritten, and while we're at it, we'll also switch foo, for bar..

capturing a $_GET variable:
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{QUERY_STRING} foo=(.*)
RewriteRule ^grab(.*) /page.php?bar=%1

would translate a link/user's request for..

http://domain.com/grab?foo=foobar

server-side, into..

http://domain.com/page.php?bar=foobar

Which is to say, the user's browser would be fed page.php (without an [R] flag in the RewriteRule, their address bar would still read /grab?foo=foobar). The variable bar would be available to your script, with its value set to foobar. This variable has been magically created, by simply using a regular ? in the target of the RewriteRule, and tagging on the first captured backreference, %1.. ?bar=%1

Note how we use the % character, to specify variables captured in RewriteCond statements, aka "Backreferences". This is exactly like using $1 to specify numbered backreferences captured in RewriteRule patterns, except for those captured inside RewriteCond statements, we use % instead of $.

You can use the [QSA] flag in addition to these query string manipulations, merge them. In the next example, the value of foo becomes the directory in the target URL, the variable file is magically created, and the original query string is then tagged back onto the end of the whole thing..
QSA Overkill!
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{QUERY_STRING} foo=(.+)
RewriteRule ^grab/(.*) /%1/index.php?file=$1 [QSA]

So a request for..

http://domain.com/grab/foobar.zip?level=5&foo=bar

is translated, server-side, into..

http://domain.com/bar/index.php?file=foobar.zip&level=5&foo=bar

Depending on your needs, you could even use flat links and dynamic variables together, something like this could be useful..


By the way, you can easily do the opposite, strip a query string from a URL, by simply putting a ? right at the end of the taget part. This example does exactly that, whilst leaving the actual URI intact..

just a demo!
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{QUERY_STRING} .
RewriteRule foo.php(.*) /foo.php? [L]
The RewriteCond statement only allows requests that have something in their query string, to be processed by the RewriteRule, or else we'd end up in that hellish place, dread to all mod_rewriters.. the endless loop. RewriteCond is often used like this; as a safety-net.
 

cooler access denied

In part one I demonstrated a drop-dead simple mechanism for denying access to particular files and folders. The trouble with this is the way our user gets a 403 "Access Denied" error, which is a bit like having a door slammed in your face. Fortunately, mod_rewrite comes to the rescue again and enables us to do less painful things. One method I often employ is to redirect the user to the parent folder..

they go "huh?.. ahhh!"
# send them up!
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)$ ../ [NC]

It works great, though it can be a wee bit tricky with the URLs, and you may prefer to use a harder location, which avoids potential issues in indexed directories, where folks can get in a loop..

they go damn! Oh!
# send them exactly there!
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)$ /comms/hardware/router/ [NC]

Sometimes you'll only want to deny access to most of the files in the directory, but allow access to maybe one or two files, or file types, easy..
deny with style!
# users can load only "special.zip", and the css and js files.
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !^(.+)\.css$
RewriteCond %{REQUEST_FILENAME} !^(.+)\.js$
RewriteCond %{REQUEST_FILENAME} !special.zip$
RewriteRule ^(.+)$ /chat/ [NC]

Here we take the whole thing a stage further. Users can access .css (stylesheet) and javascript files without problem, and also the file called "special.zip", but requests for any other filetypes are immediately redirected back up to the main "/chat/" directory. You can add as many types as you need. You could also bundle the filetypes into one line using | (or) syntax, though individual lines are perhaps clearer.

Here's what's currently cooking inside my /inc/ directory..

all-in-one control..
RewriteEngine on
Options +FollowSymlinks
# allow access with no restrictions to local machine at 192.168.1.3
RewriteCond %{REMOTE_ADDR} !192.168.1.3
# allow access to all .css and .js in sub-directories..
RewriteCond %{REQUEST_URI} !\.css$
RewriteCond %{REQUEST_URI} !\.js$
# allow access to the files inside img/, but not a directory listing..
RewriteCond %{REQUEST_URI} !img/(.*)\.
# allow access to these particular files...
RewriteCond %{REQUEST_URI} !comments.php$
RewriteCond %{REQUEST_URI} !corzmail.php$
RewriteCond %{REQUEST_URI} !digitrack.php$
RewriteCond %{REQUEST_URI} !gd-verify.php$
RewriteCond %{REQUEST_URI} !post-dumper.php$
RewriteCond %{REQUEST_URI} !print.php$
RewriteCond %{REQUEST_URI} !source-dump.php$
RewriteCond %{REQUEST_URI} !textview.php$
RewriteRule ^(.*)$ / [R,nc,l]
 

prevent hot-linking

Believe it or not, there are some webmasters who, rather than coming up with their own content will steal yours. Really! Even worse, they won't even bother to copy to their own server to serve it up, they'll just link to your content!  no, it's true, in fact, it used to be incredibly common. These days most people like to prevent this sort of thing, and .htaccess is one of the best ways to do it.

This is one of those directives where the mileage variables are at their limits, but something like this works fine for me..

how DARE they!
Options +FollowSymlinks
# no hot-linking
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?corz\.org/ [NC]
RewriteRule .*\.(gif|jpg|png)$

You may see the last line broken into two, but it's all one line (all the directives on this page are). Let's have a wee look at what it does..

We begin by enabling the rewrite engine, as always.

The first RewriteCond line allows direct requests (not from other pages - an "empty referrer") to pass unmolested. The next line means; if the browser did send a referrer header, and the word "corz.org" is not in the domain part of it, then DO rewrite this request.

The all-important final RewriteRule line instructs mod_rewrite to rewrite all matched requests (anything without "corz.org" in its referrer) asking for gifs, jpegs, or pngs, to an alternative image. Mine says "no hotlinking!" You can see it in action here. There are loads of ways you can write this rule. google for "hot-link protection" and get a whole heap. Simple is best. You could send a wee message instead, or direct them to some evil script, or something. These days, mine is a simple corz.org logo, which I  think is rather clever.
 

lose the "www"

I'm often asked how I prevent the "www" part showing up at my site, so I guess I should add something about that. Briefly, if someone types http://www.corz.org/ into their browser (or uses the www part for any link at corz.org) it is redirected to the plain, rather neat, http://corz.org/ version. This is very  simple to achieve, like this..

beware the regular expression:
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{http_host} ^www\.corz\.org [NC]
RewriteRule ^(.*)$ http://corz.org/$1 [R=301,NC]

You don't need to be a genius to see what's going on here. There are other ways you could write this rule, but again, simple is best. Like most of the examples here, the above is pasted directly from my own main .htaccess file, so you can be sure it works perfectly. In fact, I recently updated it so that I could share rules between my dev mirror and live site without any .htaccess editing..

here's what I'm currently using:
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,NC,L]
 

multiple domains in one root

If you are in the unfortunate position of having your sites living on a host that doesn't support multiple domains, you may be forced to roll your own with .htaccess and mod_rewrite. So long as your physical directory structure is well thought-out, this is fairly simple to achieve.

For example, let's say we have two domains, pointing at a single hosted root; domain-one.com and domain-two.com. In our web server root, we simply create a folder for each domain, perhaps one/, and two/ then in our main (root) .htaccess, rewrite all incoming requests, like this..

All requests NOT already rewritten into these folders, transparently rewrite..
#two domains served from one root..
RewriteCond %{HTTP_HOST} domain-one.com
RewriteCond %{REQUEST_URI} !^/one
RewriteRule ^(.*)$ one/$1 [L]

RewriteCond %{HTTP_HOST} domain-two.com
RewriteCond %{REQUEST_URI} !^two
RewriteRule ^(.*)$ two/$1 [L]

All requests for the host domain-one.com are rewritten (not R=redirected) to the one/ directory, so long as they haven't already been rewritten there (the second RewriteCond). Same story for domain-two.com. Note the inconsistency in the RewriteCond statement; !^/dir-name and !^dir-name should both work fine.

Also note, with such a simple domain & folder naming scheme, you could easily merge these two rule sets together. This would be unlikely in the real world though, which is why I left them separate; but still, worth noting.

Other general settings and php directives can also go in this root .htaccess file, though if you have any further rewrite you'd like to perform; short URL's, htm to php conversion and what-not; it's probably easier and clearer to do those inside the sub-directory's .htaccess files.
 

automatic translation

If you don't read English, or some of your guests don't, here's a neat way to have the wonderful Google translator provide automatic on-the-fly translation for your site's pages. Something like this..

they simply add their country code to the end of the link, or you  do..
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)-fr$ http://www.google.com/translate_c?hl=fr&sl=en&u=http://corz.org/$1 [R,NC]
RewriteRule ^(.*)-de$ http://www.google.com/translate_c?hl=de&sl=en&u=http://corz.org/$1 [R,NC]
RewriteRule ^(.*)-es$ http://www.google.com/translate_c?hl=es&sl=en&u=http://corz.org/$1 [R,NC]
RewriteRule ^(.*)-it$ http://www.google.com/translate_c?hl=it&sl=en&u=http://corz.org/$1 [R,NC]
RewriteRule ^(.*)-pt$ http://www.google.com/translate_c?hl=pt&sl=en&u=http://corz.org/$1 [R,NC]

You can create your menu with its flags or whatever you like, and add the country code to end of the links.. <a href="page.html-fr" id="... Want to see this page in French?

Although it is very handy, and I've been using it here for a couple of years here at the org, for my international blog readers, all two of them, heh. Almost no one knows about it, mainly because I don't have any links . One day I'll probably do a wee toolbar with flags and what-not. Perhaps not. Trouble is, the Google translator stops translating after a certain amount of characters (which seems to be increasing, good), though these same rules could easily be applied to other translators, and if you find a good one, one that will translate a really huge  document on-the-fly, do let me know!

If you wanted to be really clever, you could even perform some some kind of IP block check and present the correct version automatically, but that is outside the scope of this document. note: this may be undesirable for pages where technical commands are given (like this page) because the commands will also be translated. "RewriteEngine dessus" will almost certainly get you a 500 error page!

 

httpd.conf

Remember, if you put these rules in the main server conf file (usually httpd.conf) rather than an .htaccess file, you'll need to use ^/... ... instead of ^... ... at the beginning of the RewriteRule line, in other words, add a slash.
 

inheritance..

If you are creating rules in sub-folders of your site, you need to read this.

You'll remember how rules in top folders apply to all the folders inside those folders too. we call this "inheritance". normally this just works. but if you start creating other rules inside subfolders you will, in effect, obliterate the rules already applying to that folder due to inheritance, or "decendancy", if you prefer. not all the rules, just the ones applying to that subfolder. a wee demonstration..

Let's say I have a rule in my main /.htaccess which redirected requests for files ending .htm to their .php equivalent, just like the example at the top of this very page. now, if for any reason I need to add some rewrite rules to my /osx/.htaccess file, the .htm >> .php redirection will no longer work for the /osx/ subfolder, I'll need to reinsert it, but with a crucial difference..

this works fine, site-wide, in my main .htaccess file
# main (top-level) .htaccess file..
# requests to file.htm goto file.php
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\.htm$ http://corz.org/$1.php [R=301,NC]

Here's my updated /osx/.htaccess file, with the .htm >> .php redirection rule reinserted..

but I'll need to reinsert the rules for it to work in this sub-folder
# /osx/.htaccess file..
Options +FollowSymlinks
RewriteEngine on
RewriteRule some rule that I need here
RewriteRule some other rule I need here
RewriteRule ^(.*)\.htm$ http://corz.org/osx/$1.php [R=301,NC]

Spot the difference in the subfolder rule, highlighted in red. you must add the current path to the new rule. now it works again, and all the osx/ subfolders will be covered by the new rule. if you remember this, you can go replicating rewrite rules all over the place.

If it's possible to put your entire site's rewrite rules into the main .htaccess file, and it probably is; do that, instead, like this..

it's a good idea to put all your rules in your main .htaccess file..
# root /.htaccess file..
Options +FollowSymlinks
RewriteEngine on
# .htm >> .php is now be covered by our main rule, there's no need to repeat it.
# But if we do need some /osx/-specific rule, we can do something like this..
RewriteRule ^osx/(.*)\.foo$ /osx/$1.bar [R=301,NC]

Note, no full URL (with domain) in the second example. Don't let this throw you; with or without is functionally identical, on most servers. Essentially, try it without the full URL first, and if that doesn't work, sigh, and add it - maybe on your next host!

The latter, simpler form is preferable, if only for its tremendous portability it offers - my live site, and my development mirror share the exact same .htaccess files - a highly desirable thing.

By the way, it perhaps doesn't go without saying that if you want to disable rewriting inside a particular subfolder, where it is enabled further up the tree, simply do:

handy for avatar folders, to allow hot-linking, etc..
RewriteEngine off
 

conclusion

In short, mod_rewrite allows you to send browsers from anywhere to anywhere. You can create rules based not simply on the requested URL, but also on such things as IP address, browser agent (send old browsers to different pages, for instance), and even the time of day; the possibilities are practically limitless.

The ins-and outs of mod_rewrite syntax are topic for a much longer document than this, and if you fancy experimenting with more advanced rewriting rules, I urge you to check out the apache documentation.

If you have apache installed on your system, there will likely be a copy of the apache manual, right here, and the excellent mod_rewriting guide, lives right here. do check out the URL Rewriting Engine notes for the juicy syntax bits. That's where I got the cute quote for the top of the page, too.
 
;o)
(or
 
 

troubleshooting tips..

rewrite logging..

When things aren't working, you may want to enable rewrite logging. I'll assume you are testing these mod_rewrite directives on your development mirror, or similar setup, and can access the main httpd.conf file. If not, why not?  Testing mod_rewrite rules on your live domain isn't exactly ideal, is it? Anyway, put this somewhere at the foot of your http.conf..

Expect large log files..
#
# ONLY FOR TESTING REWRITE RULES!!!!!
#
RewriteLog "/tmp/rewrite.log"
#RewriteLogLevel 9
RewriteLogLevel 5

Set the file location and logging level to suit your own requirements. If your rule is causing your Apache to loop, load the page, immediately hit your browser's "STOP" button, and then restart Apache. All within a couple of seconds. Your rewrite log will be full of all your diagnostic information, and your server will carry on as before.

Setting a value of 1 gets you almost no information, setting the log level to 9 gets you GIGABYTES! So you must remember to comment out these rules and restart Apache when you are finished because, not only will rewrite logging create space-eating files, it will seriously impact your web server's performance.

RewriteLogLevel 5  is very useful, I find.

Fatal Redirection

If you start messing around with 301 redirects [R=301], aka. "Permanently Redirected", and your rule isn't working, you could give yourself some serious headaches..

Once the browser has been redirected permanently  to the wrong address, if you then go on to alter the wonky rule, your browser will still  be redirected to the old address (because it's a browser thing), and you may even go on to fix, and then break  the rule all over again without ever knowing it. Changes to 301 redirects can take a long time to show up in your browser.

Solution: restart your browser, or use a different one.

Better Solution: Use [R] instead of [R=301] while you are testing . When you are 100% certain the rule does exactly as it's expected to, then  switch it to [R=301] for your live site.
 

debug-report.php
A php script to make your mod_rewrite life easier!

When things aren't working as you would expect, you probably won't have to enable rewrite logging to get the information you need. What's usually required is no more than a quick readout of all the current variables, $_GET array, and so on; so you can see exactly what happened to the request.

For another purpose, I long ago created debug.php, and later, finding all this information useful in chasing down wonky rewrites, created a "report" version, which rather than output to a file, spits the information straight back into your browser, as well as $_POST, $_SESSION, and $_SERVER arrays, special variables, like __FILE__, and much more.

Usage is simple; you make it your target page, so in a rule like this..

RewriteRule ^(.*)\.html$ /catch-all.php?var=$1

You would have a copy of debug-report.php temporarily renamed to catch-all.php in the root of your server, and type http://testdomain.org/foobar.html into your address bar and, with yer mojo working, debug-report.php leaps into your browser with a shit-load of exactly the sort of information you need to figure out all this stuff. When I'm messing with mod_rewrite, debug-report.php saves me time, a lot. Also, it's free..

 
 
 
 

Before you ask a question..

Firstly, read this at least once in your life. I insist!

NOTE: THIS IS NOT A COMMUNITY. And I am not your free tech dude. Sure, folk sometimes drop back in, but realistically, the chances of someone else coming along and answering your tech question are about as close to zero as it gets; almost no one sticks around but me, the guy who wrote all that text (above).

If you can't be bothered to read the article, I can't be bothered responding. Capiche? I do read all comments, though, and answer questions about the article. I'm also keen to discuss anything you think I've missed, or interesting related concepts in general.

If you are still sure that you want to post your own, personal, tech question, then please ensure that you first, either..

a) Have read the article (above) and have tried "everything" yourself; in which case; post the exact code that isn't working (preferably inside [pre][/pre] tags), or else..

b) Pay me. The PayPal button is at the top right of the page.

Other posts will be ignored and/or deleted.

cbparser powered comments..

previous comments (thirty two pages)   show all comments

simone - 07.07.08 9:22 am

Hi, tnx for this interesting article.

I have a problem with url rewriting, i need to use it to do deeplinking with SWFAddress,
so I want to rewrite

/products/productname/


to something like

/#/products/productname


the rule i wrote is:

RewriteRule ^products/([A-Za-z]*)/$ /#/products/$1/ [R]


this seems to work nice except for a simple issue:
the #
is urlencoded by apache into
%23

so the final address shown in the address bar is

http://www.mysite.com/%23/products/bonarda/

instead of the desired
http://www.mysite.com/#/products/bonarda/


any hint on this issue?

bye
simone


Tom - 15.07.08 10:39 pm

WOW, thanks for the wicked examples!
Espicially happy with your languages translator!!
Wicked idea!




ashwani - 16.07.08 11:55 am

.htaccess provide comlete™


Dman - 18.07.08 9:17 pm

I have the hardest time getting mod rewrite to work with Tomcat.

Here is our situation. We run Apache2.2 and Tomcat5.5.2.3 together. Apache does nothing but forward requests to Tomcat instances via Mod JK workers.

Mod Rewrite is loaded and working on the Apache side. Example if I create 2 files: test1.html and test2.html and my simple rule are as followed.

I have a .htaccess at the root of Apache
RewriteEngine On
RewriteRule ^/?test1\.html$ test2.html

User type http://www.apachehost.com/test1.html he gets the content of test2.html. Great!

I incorporated this in httpd.conf file and hoping that it would do the same but I am getting test1.html content only:

Example: If I type http://www.tomcathost.com/test1.html I just get the test1.html page instead of the test2.html content.

<VirtualHost *:80>
ServerName www.tomcathost.com
Options +FollowSymlinks
JkOptions +ForwardURICompat
JkLogFile logs/mod_jk.log
JkMount /* fadworker
ErrorLog logs/www.tomcathost.com-error.log
#CustomLog logs/www.tomcathost.com-access.log common
LogLevel Error
JkUnMount /admin/* fadworker
JkUnMount /manager/* fadworker
JkUnMount /host-manager/* fadworker
JkUnMount /probe/* fadworker

RewriteEngine On

RewriteLog logs/mod_rewrite.log
RewriteLogLevel 4

RewriteRule ^/?test1\.html$ test2.html
</VirtualHost>

My question is am I missing something here?

Mod JK is loaded before Mod Rewrite.

Dman, remember, for httpd.conf use, you need to add a slash to the start, e.g. /test2.html, or else you'll get a 400, Bad Request. As for Tomcat, I have zero experience. ;o)


Evan - 25.07.08 1:47 pm

Wicked cool article. Just starting messing with apache and this stuff, after a good explanation like the one above, really makes me happy. smiley for :D


micmac - 27.07.08 11:57 am

Neat approach and performance, sheding light in an dark area, typical cause of lots of frustrations. By this help I could improve a lot the security of my server.

But also here are examples, where a given code won't work in reality. It will be, because too fast the practitioner gains the impression, he understood the language systematics and thus creates on this base new varieties of options. I understand, that not any sample, presented in such a broad collection is tested first. Who likes 500 server error on his life system?

A typical sample, not covered here anymore (?) is the hiding of the .htaccess. Long survey finally gave, the given good codes only apply for .httpd server config and don't apply for the .htaccess itselfs (fine 500 disturbances...). The server provider (US) does not even understand, what the customer is asking, and falsly claims, the file is hidden already. That is valid so far any .ht is a hidden file, but it can be seen by any simple remote access via web.

My latest sample the simple RewriteRule. The given code to rewrite URL does not work, because the new URL contains a "?" for PHP POST command and that can't be masked by ESC, when the own server is set up for a certain ISO character set, for what are good reasons to stick with.

A limit of information is, that the given samples are only explained in short. Namely the definition of expressions like (^/y) in the samples is not satisfactorily covered by the table of valid forms. The same goes for Apache genuine web-manuals, written by machines for machines. Thus the reader here only can import given samples, to the utmost customizing them, but finally does not understand the rules. That a few minutes ago also brought good 500 errors to my readers or banned them from pages, now unintentionally restricted by authentication.

But such, it seems, is the server config world ...




Rob - 01.08.08 6:23 pm

@simone
You need to tell mod_rewrite not to urlencode your rewritten URL, you do that with the NE (noescape) flag. So you should use something like this:

RewriteRule ^products/([A-Za-z]*)/$ /#/products/$1/ [NE,R]


Michael - 05.08.08 5:57 pm

Thank you for a great article on .htaccess. I am a novice in this area and I really needed some help. I am running a demo video sharing website (I am just experimenting on how the script will work). After installing the script, I uploaded some test video to see if the script is functioning as it was intended by the script authors. The script is function very well as promised. Today I was playing around typing the url of that website on my browser and I was shocked on what I have just found out. All of my converted video files (flv) are saved by the script inside the folder called "uploads". If I type MyDomainDotCom/uploads on my browser, it will show all the files in that folder and I don't want other people to be viewing and downloading this files using their browser.

I was searching about the topics on how I can protect this folder, and I found one from other website that one can just throw in an .htaccess file inside the folder and it will disallow the access. It was easy I said to myself. I have created the suggested .htaccess file with the following code below. This is from one of the forum I visited this morning.

Order allow,deny
allow from myDomainDotCom


Now my problem with the code above is that the embed code coming from my site cannot play the video. I only want to restrict browsers from viewing the uploads folder, but at the same time the files inside it will be still accessible by my embed code, and by myDomainDotCom php files.

Can somebody please help, or guide me where to start.

Thank you very much for your time.

Michael


cor - 05.08.08 6:56 pm

Michael, the .htaccess code you have is wonky. I recommend you start at the correct page, and follow *my* examples, instead!

allow from myDomainDotCom

..is a nonsense. Mainly because requests, even internal HTTP requests won't be coming from that domain (that's assuming Apache can even translate the domain name into an actual IP). If they are coming from anywhere, they are coming from 127.0.0.1, aka "localhost".

Having said all that, you need to keep in mind that if the user's browser needs to access the files directly, you MUST allow access to the folder. Only if your script accesses the media files via the file system (not HTTP request) and then serves them up to the users browser via some kind off "passthru" functionality, only then can you deny all direct access to the folder. If it does use a local HTTP request, then you can deny all except 127.0.0.1. The former system is better, though.

But like I say, if you need more, go to part one, where I deal with all this (this page is about rewriting), and check out the examples there and in the comments.

Have fun!

;o)
(or

ps. thanks for all the flowers guys, you know that's just food for my funky new front-page random quote script! smiley for ;)


Predrag - 08.08.08 9:56 pm

Wow, you tutorial is amazing....

I have one problem.

I have a site on www.site1.com with all content.
And I have second site on www.site2.com who must when someone go on address www.site2.com to show all content from www.site1.com but in address line in browser must see www.site2.com.
Everything must be like is two different sites but it is only one with two domain name.

Can you help me about this? How can I do this with .htaccess?

Thanks,
Predrag

If they are on the same server, simply use regular internal redirects pointing to the file system. If they are on different servers, you can't use .htaccess to cloak the real URL, as an external redirect would be required. In that case, use a fram or similar construct. - OMG! I just recommended someone use a frame! smiley for :eek: I'll burn in hell for that! ;o)


Justin - 11.08.08 4:02 am

Okay, new problem.

My .txt files, .js files, and .flv files are all blocked now...and the .txt and are still usable in the way i want...but my .flv videos still aren't. And my .js file wont do what it's told on an .html page that accesses it...

And, on more of a side note, every time I upload a new .htaccess, close out of the ftp editor, and open it again, the .htaccess file is there, because i know it is, and because it's still in effect, but i can't find it in the ftp editor. I'm confused. It doesn't even ask me if I want to overwrite the file when I upload a new .htaccess . How can I fix this?

Thanks,
Justin


BlackHatEmpire.com - 13.08.08 2:31 pm

Congrats on a very good comprehensive HTACCESS guide. Well done, was very helpful and structed well. I wish more websites would be like yours!


gulflee - 15.08.08 3:24 am

Hi I had re-direct the url

(category)
www.domain.com/?p=12 --> www.domain.com/category/another-abc.html
and
(sub-category)
www.domain.com/?p=1 --> www.domain.com/category/subcategory/abc.html

but I dun want the subcategory i m thinking is it possible to rewrite the URL from

www.domain.com/category/subcategory/abc.html --> www.domain.com/category/abc.html

thanks in advance.



Taek - 19.08.08 5:31 am

I am looking to use url re-write rule and I'm not sure what I can use to do what I am looking for i will setup my httpd.conf accordingly but i would like to doing something like

media.somedomain.net/data/file.jpg
to
files.media.somedomain.net/file.jpg

also would like to do something like
media.somedomain.net/data/someuser/file.jpg
to
someuser.media.somedomain.net/file.jpg

I know this seems stupid but I plan on having a small image hosting system and this would help alot.


Jaunty Mellifluous - 19.08.08 3:39 pm

Hi,

Thanks for the nice tutorial.

I'm using this code from your examples to run my site from a subfolder in my root hosting space.

..meaning I've placed my site in a folder inside my root folder. /root/roadsout/ << like that.

RewriteEngine on
Options +FollowSymlinks
RewriteCond %{HTTP_HOST} roadsout.com
RewriteCond %{REQUEST_URI} !^/roadsout
RewriteRule ^(.*)$ roadsout/$1 [L]


so that's the code. It works fine. But the problem is, when I browse to the links within my site, the url becomes something like this, http://www.roadsout.com/roadsout/miley..

I want to url to look like http://www.roadsout.com/miley.. all the time. So that it doesn't show the extra subfolder inside my hosting space.

Please help. Thanks.


AskApache - 20.08.08 11:41 am

@Corz

Hi I just published an advanced mod_rewrite tutorial that you might find interesting. It shows some sick methods for viewing the variables available to the mod_rewrite engine by adding them to the REQUEST headers. Once set up, you simply request a debugging file like your "du" php file and variables that were once hidden from the php interpreter are now populated.

Love the site and I've been waiting for htaccess3.php for quite some time now...

-AA


Lws - 23.08.08 11:43 pm

Hi all,
I have this url www.domain.com/category but i want category.domain.com
Can you give tips, please?
Thank you


ckyeu - 25.08.08 9:11 am

This article is very good. however, I have run into a problem when I want to rewrite this url http://mydomain.com/memberprofile.php?user=xxx yyy to maybe http://mydomain.com/xxx-yyy or http://mydomain.com/xxx+yyy. I was able to rewrite for http://mydomain.com/memberprofile.php?user=xxx to http://mydomain.com/xxx. It is a live site and I didnt foresee that people would register with names with spaces :(. (the name has a space i.e. xxx yyy)

Thank you guys in advance for your help..

Thanks for this tutorial too..smiley for :)


Peter - 26.08.08 3:54 am

Similar to this guy's question:

Wow, you tutorial is amazing....

I have one problem.

I have a site on www.site1.com with all content.
And I have second site on www.site2.com who must when someone go on address www.site2.com to show all content from www.site1.com but in address line in browser must see www.site2.com.
Everything must be like is two different sites but it is only one with two domain name.

Can you help me about this? How can I do this with .htaccess?

Thanks,
Predrag

My question is very similar except that I'm building a Joomla site that is absorbing two or three sites that have their own domain names.

Example, say I had a site called "chevy.com" and I was rebuilding it, bringing into it sites like detroitchevy.com and toledochevy.com, as they were going to be different "sections" within this chevy.com site running on Joomla. The puzzle for me is this: I want those users who are going to detroitchevy.com to go to the detroit chevy "section" of chevy.com and keep detroitchevy.com in the URL somehow. The same would hold true for toledochevy.com. Is this even possible?


Andy - 28.08.08 3:46 pm

Hi

Excellent site; I have already used some of the ideas. I think you forgot to talk about switches [NC] etc - you said you would come onto those later.

Thanks
Andy


doru - 29.08.08 6:01 pm



sorry to badder you

my site is php site

I own an web site and hire someone to make my links shorter.

but they made it in 9 folder

domain.com/a/b/c/d/e/f/g/h/j.html

what I want is domain.com/state/city-category-produs/

and he said is not possible , is he right ?


 

leave a comment, become part of this site!


First, confirm that you are human by entering the code you see..

(if you find it difficult to read, refresh the page for a new code)


Enter the 5-digit code this text sounds like : lower-case ee, Upper-Case Kay, thuree, lower-case em, Upper-Case Pee


 
 
[site notice]

If you give a shit, BUY A SHIRT!