views:

34

answers:

2

Hi All,

This should be simple but I cannot figure it out. I have this very simple mod_rewrite rule and it just doesn't want to work. This is the entire contents of the .htaccess file.

RewriteEngine On
RewriteRule ^([A-Za-z0-9-_/\.]+)/?$ index.php?page=$1 [L]

If I call the URL domain.com/foo it should rewrite it to index.php?page=foo. But instead, it rewrites it to index.php?page=index.php. I have tried multiple URLs:

  • index.php?page=foo
  • index.php
  • /foo
  • /

In all cases, PHP acts as if 'page' is set to "index.php". It isn't a fault with index.php because I replaced the entire contents of index.php with a script that simple echoed the value of 'page' and it still comes out as index.php.

Really lost where I'm going wrong here, any help would be awesome!

Thanks

Adrian

A: 

I think this is what your looking for. Unfortunately it doesn't really work well if the URL has other GET arguments (IE, /some/url/path?page=1).

RewriteEngine On
RewriteRule ^(.*)$ index.php?page=$1 [L]

Better idea.

RewriteEngine On
RewriteRule ^(.*)$ index.php [L,QSA]

The QSA flag will forward the GET params and then in index.php use $_SERVER['REQUEST_URI'] and parse_url to route the request.

From http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html:

'qsappend|QSA' (query string append)
This flag forces the rewriting engine to append a query string part
in the substitution string to the existing one instead of replacing it.
Use this when you want to add more data to the query string via a rewrite rule.
Kendall Hopkins
For the time being I won't have multiple get arguments, I just need this to work for now. I tried what you gave me and it still produces the same result.
Adrian Trimble
+1  A: 

Any reason you can't use something simpler, such as:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1 [L]

If you're trying to keep existing pages from being re-written, then the !-f will take care of that (if file does not exist and if directory does not exist, then re-write)

Marc B
I actually hadn't thought of that (avoiding re-writing actual pages), but that is definitely something I need to do! This works for me, thanks!
Adrian Trimble