Dear Wiki user,

You have subscribed to a wiki page or wiki category on "Httpd Wiki" for change 
notification.

The following page has been changed by slive:
http://wiki.apache.org/httpd/Recipes/QueryString

The comment on the change is:
This has become a FAQ.

New page:
= Manipulating the Query String =

The query string is the part of the URL that follows the question mark (?). It 
is often used to pass parameters to CGI scripts or other dynamic pages. It is 
typically available in the QUERY_STRING environment variable.

The typical URL-manipulation directives such as {{{Redirect}}}, {{{Alias}}}, 
and {{{RewriteRule}}} cannot directly access the query string. But 
{{{mod_rewrite}}} can be used to add, remove, or modify the query string. The 
trick is to use a {{{RewriteCond}}} to match against the {{{%{QUERY_STRING} }}} 
variable and, if necessary, the {{{[QSA]}}} flag to append to an existing query 
string.

Some examples follow. These examples all assume that they are placed in the 
main server configuration file. If they are placed in a {{{<Directory>}}} 
section or {{{.htaccess}}} file, the {{{RewriteRule}}} will need to be modified 
accordingly. Also, these examples can all be transformed from internal alias to 
external redirects by adding the {{{[R]}}} flag to the {{{RewriteRule}}}.

Be cautious when dealing with complex query strings, since the order of the 
variables is often arbitrary. 

=== Removing the Query String ===

Delete the query string entirely.

{{{
RewriteRule (.*) $1?
}}}

=== Adding to the Query String ===

Keep the existing query string using the Query String Append flag, but add 
{{{newstuff}}} to the end.

{{{
RerwriteRule (.*) $1?newstuff [QSA]
}}}

=== Rewriting For Certain Query Strings ===

Rewrite URLs like {{{http://example.com/page1?stuff}}} to 
{{{http://example.com/page2?stuff}}} (but don't rewrite if {{{stuff}}} isn't 
present.

{{{
RewriteCond %{QUERY_STRING} ^stuff$
Rewrite ^/page1 /page2
}}}

=== Modifying the Query String ===

Change any single instance of {{{foo}}} in the query string to {{{bar}}} when 
accessing {{{/path}}}.  Note that {{{%1}}} and {{{%2}}} are back-references to 
the matched part of the regular expression in the previous {{{RewriteCond}}}.


{{{
RewriteCond %{QUERY_STRING} ^(.*)foo(.*)$
RewriteRule /path /path?%1bar%2
}}}

=== Making the Query String Part of the Path ===

Take a URL of the form {{{http://example.com/path?var=val}}} and transform it 
into {{{http://example.com/path/var/val}}}.
{{{
RewriteCond %{QUERY_STRING} ^(.*)=(.*)$
RewriteRule ^/path /path/%1/%2
}}}

=== Making the Path Part of the Query String ===

Essentially the reverse of the above recipe.

{{{
RewriteRule ^/path/(.*)/(.*) /path?$1=$2
}}}

Reply via email to