views:

778

answers:

4

Hi, I'm trying to set up a simple rewrite rule to convert a url such as:

"index.php?page=login"

to something like

"page/login"

However, I keep getting 404 errors.

Can anyone suggest why the following might not be working?

.htaccess:

RewriteEngine on

RewriteRule ^page/([^/\.]+)/?$ index.php?page=$1 [L]

rewriteEngine off

I'm quite new to this and any advice would be greatly appreciated. Thanks.

A: 

Make sure you use RewriteBase.

These are the rules I normally use. They say that any request that is not a file or directory, is handled by index.php In the script, the requested URI is available through $_SERVER['REQUEST_URI'].

RewriteEngine On
RewriteBase /some_dir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /some_dir/index.php [L]
gnud
+2  A: 

I think you may have it bacwards. Do you want the user to type in this?

http://site.com/page/login

?

That's the more logical situation. If so, do this:

RewriteEngine On
RewriteBase /
RewriteRule ^/page/login$ /index.php?page=login [L]

Or, more generally:

RewriteRule ^/page/(\w+)$ /index.php?page=$1 [L]
cletus
Good call, this helped me fix my issue too, I was working in /clients and was getting 404's till I added in a `RewriteBase /clients` and removed my `(?:clients)` from my regex
DavidYell
A: 
RewriteEngine on

RewriteRule ^page/([^/.]+)/?$ index.php?page=$1 [L]

rewriteEngine off

Why do you turn the RewriteEnginge off?

VolkerK
Thanks guys, it's working now.My problem was due to the RewriteBase, or rather the lack of it.
A: 

VolkerK makes a good point: don't use both RewriteEngine on and RewriteEngine off, because you're not turning the rewriting engine on, adding a rule, and turning it off again. Apache configuration does not work like programming, where you have a set of instructions that the computer executes in order. You can imagine it more like this: when Apache parses its configuration files (like .htaccess), it first reads in all the directives and sorts them out into a natural order in which they will be applied. It's more like initializing the values of variables at the start of a program, where the outcome is generally the same regardless of what order you write the statements in.

In your case, specifying both RewriteEngine on and RewriteEngine off in the same file is likely to confuse Apache, since (in my little metaphor) when Apache sorts the directives into their "natural" order, it'd wind up with something like

RewriteEngine on
RewriteEngine off
RewriteRule ...

which would presumably turn the rewrite engine off. But of course, what actually happens is more complicated than just sorting directives into a list, so you can't really tell what Apache will do with a file like yours. Just don't try to turn the rewrite engine on and off for different parts of the file, and remember that Apache's configuration directives aren't just statements to be run in order.

David Zaslavsky