0

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?

2 Answers 2

3

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]
Sign up to request clarification or add additional context in comments.

4 Comments

I've just tried adding that rule and the result is still the same.
Changing the RewriteCond regex to: !index\.php gets the desired result but then /framework/testing/index.php won't redirect (for obvious reasons)
@Peter Horne: use RewriteCond %{REQUEST_FILENAME} !-f then. It is suitable in most cases
That's an improvement but I've just realised RewriteCond $1 !^index\.php solves the problem perfectly. Thanks for your help!
3

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

3 Comments

I don't understand what you mean, could you expand on this please? There is no query string in the original request, so without the rules I've added then $_GET['q'] would be empty.
@Peter Horne: what can't you understand exactly? The original request is in GET's q variable, and to avoid infinity rewriting loop - follow the Jon Lin answer (which is correct and should work)
I misunderstood and thought you were talking about the incoming request (before it reaches my server) having ?q= already set! Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.