Forum Moderators: phranque

Message Too Old, No Replies

RewriteRule

"if not" condition

         

wizpl

2:11 am on Oct 25, 2006 (gmt 0)

10+ Year Member



I need a rule which would rewrite
www.domain.com?bar into www.domain.com/page?foo=bar
but only if there is no "=" in the request.
so that e.g. www.domain.com?other=option is left unaltered.

is it possible?

jdMorgan

12:48 am on Oct 26, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Assuming that the code is intended for use in .htaccess and not in a server config-level file, and that you want to do an external redirect to 'correct' search engine listings, you could use something like this:

# If query does not contain foo=bar
RewriteCond %{QUERY_STRING} !foo=bar&?
# but does contain?bar&<anything>, <anything>&bar, <anything>&bar&<anything>, or only bar
RewriteCond %{QUERY_STRING} ^(.*&)?bar(&.*)?
# then remove bar and insert foo=bar in remaining query string (on domain home page only)
RewriteRule ^$ http://www.example.com/?%1foo=bar%2 [R=301,L]

For more information, see the documents cited in our forum charter [webmasterworld.com] and the tutorials in the Apache forum section of the WebmasterWorld library [webmasterworld.com].

Jim

wizpl

2:06 am on Oct 27, 2006 (gmt 0)

10+ Year Member



thanks, I have studied your example and it lead me to a single line pattern that should work, but it doesn't:

RewriteRule ^\?([^=&]+)$ /reel?list=$1

I escaped the "?" but it does not seem to match the question mark.
If I change "\?" to e.g. "x", all works fine though.

RewriteRule ^x([^=&]+)$ /reel?list=$1

How can I mach a single "?" in a pattern?

jdMorgan

2:43 am on Oct 27, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You can't. See my post above.

Jim

jdMorgan

3:06 am on Oct 27, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The problem is that everything after the "?" is a query string.

The query string is not included in the URL-path examined by RewriteRule. Instead, Apache places everything after "?" into the variable %{QUERY_STRING} and handles it separately from the URL.

To further clarify: A query string is not part of a URL. Instead, it is data attached to a URL to be passed to the resource at that URL.

If you request "http://example.com/page.php?foo=bar" from your server, then

http is copied to the variable %{SERVER_PROTOCOL}
example.com is copied to %{HTTP_HOST}
page.php is copied to an internal variable testable by RewriteRule
/page.php is copied to %{REQUEST_URI}
foo=bar is copied to %{QUERY_STRING}
The "?" is dropped, and does not appear in any of the above variables; it serves only as a delimiter between the URL and the query string.

You may test the original request line sent by the browser, which look something like this

GET /page.php?foo=bar HTTP/1.1

by using

RewriteCond %{THE_REQUEST} <regex pattern here>

but the code I posted above is simpler.

Jim