Ahmed Medhat
Ahmed Medhat

Reputation: 13

htaccess and php routing

I was learning today about Rewrite and PHP routing. I wrote the following .htaccess file:

    RewriteEngine On
    RewriteRule ^(.+)$ testing.php?url=$1 [NC,L]

The testing.php has the following code:

    <?php
       echo $_GET["url"];
    ?>

When I enter the following URL for example: http://localhost/tests/Hello The following is shown in the browser:

     testing.php

But I am expecting "Hello" to show instead of "testing.php". I tried to change NC to QSA and it worked successfully but why the first case is not working?

Thank you.

Upvotes: 0

Views: 520

Answers (2)

Jonathan
Jonathan

Reputation: 250

It's likely that the URL is being rewritten more than once.

The first time rewrites /Hello to testing.php but then internally a separate request is made to testing.php and ran through the rewrite engine again. That will give you testing.php as the URL parameter.

Using QSA means that on the second request it is appending to the query string as opposed to overwriting it. If you looked at $_SERVER['QUERY_STRING'] you would likely see something like url=testing.php&url=Hello (or similar) and php is just using the last value in url.

Using NC is not necessary as the pattern you are using has no case (.+ matches one or more of any character regardless of case).

Using L means to stop processing rules in this request, but doesn't stop processing rules in subsequent requests (including transparent/internal subsequent requests).

Usually this is fixed by telling mod_rewrite to ignore the request if it is made to a file that exists using a RewriteCond like:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ testing.php?url=$1

Which tells apache that if the requested filename is not a file and not a directory, process the rule. With this in place, the request to testing.php will see the file exists, condition fails and so the rule isn't processed additional times. Nothing would stop additional rules from applying though if they exist. And also, just an FYI, conds only apply to the very next rule. So if you multiple rules, you need these cond for each of them.

Upvotes: 1

samyok nepal
samyok nepal

Reputation: 557

QSA stands for Query-String-Append, which means that the Query string that was first sent gets appended. With NC, you were only doing nocase, meaning that the RewriteRule will be matched in a case-insensitive manner.

L just means that RewriteRule will stop processing it after that rule.

Upvotes: 0

Related Questions