Peter Horne
Peter Horne

Reputation: 6846

mod_rewrite variable always == 'index.php'

I have the following file structure:

/framework
    /.htaccess
    /index.php

and the following rules in my .htaccess file:

<IfModule mod_rewrite.c>

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

</IfModule>

When I navigate to http://localhost/framework/example I would expect the query string to equal 'framework/example' but instead it equals 'index.php'. Why? And how do I get the variable to equal when I'm expecting it to?

Upvotes: 0

Views: 830

Answers (2)

Jon Lin
Jon Lin

Reputation: 143906

Your rewrite rules are looping. Mod_rewrite won't stop rewriting until the URI (without the query string) is the same before and after it goes through the rules. When you originally request http://localhost/framework/example this is what happens:

  1. Rewrite engine takes /framework/example and strips the leading "/"
  2. framework/example is put through the rules
  3. framework/example gets rewritten to index.php?q=framework/example
  4. Rerite engine compares the before and after, framework/example != index.php
  5. index.php?q=framework/example goes back through the rewrite rules
  6. index.php gets rewritten to index.php?q=index.php
  7. Rewrite engine compares the before and after, index.php == index.php
  8. Rewrite engine stops, the resulting URI is index.php?q=index.php

You need to add a condition so that it won't rewrite the same URI twice:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/index\.php
RewriteRule ^(.*)$ index.php?q=$1 [L]

Upvotes: 3

zerkms
zerkms

Reputation: 254944

Because you've rewritten the url with RewriteRule and have already put the previous path to the q. So just use $_GET['q']

Upvotes: 3

Related Questions