Adrian Trimble
Adrian Trimble

Reputation: 259

Why won't this simple RewriteRule work?

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:

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

Upvotes: 0

Views: 170

Answers (2)

Kendall Hopkins
Kendall Hopkins

Reputation: 44104

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.

Upvotes: 0

Marc B
Marc B

Reputation: 360702

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)

Upvotes: 2

Related Questions