8

I'm trying to learn a bit of .htaccess and am really anxious on what it can do. I saw a snippet online but can't get it to work, it basically goes like this If a query string does not have a certain value, redirect it to index.php instead or some other page. How do I do that?

This looks for the value apples:

www.domain.com/somefile.php?a=apples&b=xyz

This will redirect to index.php instead:

www.domain.com/somefile.php?a=stinkycheese&b=xyz

1 Answer 1

26

You need to use the %{QUERY_STRING} variable inside a RewriteCond. So for example, if you don't want to redirect if there exists a redirect=no in the query string, it would look like this:

RewriteCond %{QUERY_STRING} !(^|&)redirect=no($|&)
RewriteRule . /index.php [L]

So if the RewriteCond fails (it has a redirect=no in the query string), then do not apply the following rule, which rewrites whatever the request URI is to /index.php. The actual rule that you need may be different, but using RewriteCond and %{QUERY_STRING} is the basic idea that you want.

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

3 Comments

Thanks a lot Jon, that really helped a lot. Since .htaccess can scan queries using QUERY STRING can it also delete it parts of it? For example, it strips out redirect=no after doing the checking if it exists (or does not exist, depending on usage).
You can match everything that isn't redirect=no and use backrefernces (%1, %2, %3, etc) to include it. Something like RewriteCond %{QUERY_STRING} ^(.*)redirect=no&?(.*)$ then in your rule: RewriteRule . /index.php?%1%2 [L]
Would you know any worthy web post which talks about using backreferences (%1, %2,%3, etc.)? I'd like to learn more about the sample code you just posted.

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.