0

Let's start with an example:

So requested URL would be: www.domain.com/product/hdd/samsung

I want to have a rewrite rule to get index.php and save everything after www.domain.com into php variable. So, substituted page would be for example www.domain.com/index.php?query=product/hdd/samsung. But I'am unable to write correct rule.

I tried this:

RewriteRule ^/(.*)$ index.php?query=$1 [NC,L]

The code above isn't working. I want to use the query in PHP code in the index.php:

if(isset($_GET["query"] )) {
   $query=$_GET["query"];
}

I find out, there is possibility to get $query via $_SERVER['QUERY_STRING'] instead of mod_rewrite, am I right?

For my PHP application is variable $query critical, because it's used for loading templates.

Questions: What solution would you recomand me? To use $_SERVER variable or mod_rewrite? If mod_rewrite, how to write correct RewriteRule?

Thank you

4
  • That rule looks fine to me. Can you test some simpler rules to verify the rewrite rule module is applied and running properly? Commented Apr 20, 2012 at 23:36
  • Make sure you have RewriteEngine on somewhere. Commented Apr 20, 2012 at 23:36
  • Rewrite Engine is working properly (It's on). If I use the rule above, I get 404 Error. I'am testing it on localhost (wamp server). Commented Apr 20, 2012 at 23:47
  • The best rule I have been able to write is: RewriteRule /(.*) index.php?query=$1 [NC,L], but I only get string after the second slash (if there is second slash or I get 404 error). Commented Apr 20, 2012 at 23:52

1 Answer 1

1

Try this:

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?query=$1 [NC,L]

If your site is not in your server's root dir, change RewriteBase to /some/subdir/.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! Yes, Its working! But it removes parameters, e.g www.domain.com/a/b/c?sort=price. (I get index.php?query=a/b/c). I need somehow store whole string (sort=price). The best solution would be to get index.php?query=a/b/c&sort=price. I actually just need one parameter (sort). Is it even possible?
I'm quite sure I did something wrong, because I couldn't get the ?sort=price with the rewrite rule. It's like it never existed. So I thought about parsing that part with php directly. Using lafor's code, you request the correct php file, and inside that file, you get the sort part with this code: pastebin.com/vLMNSCyK . I hope it helps.

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.