1
2
3
4
RewriteEngine On
RewriteBase /
RewriteRule ^ttt/tags$ /cgi-bin/t1.pl [L]
RewriteRule ^ttt/tags/(.*) /cgi-bin/t1.pl?-tags=$1 [L]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#!/usr/bin/perl use 5.010; use strict; use warnings; print "Content-Type: text/plain\n\n"; say qq{ENV REQUEST_URI = $ENV{REQUEST_URI}}; say qq{ENV QUERY_STRING = $ENV{QUERY_STRING}}; use CGI::Simple; my $c = CGI::Simple->new; say "\nCGI-Modul:"; say $c->query_string(); say $c->param('-tags');
1
2
3
4
5
6
ENV REQUEST_URI = /ttt/tags?-tags=test%26More,A,C%26A
ENV QUERY_STRING = -tags=test%26More,A,C%26A
CGI-Modul:
-tags=test%26More%2CA%2CC%26A
test&More,A,C&A
1
2
3
4
5
6
ENV REQUEST_URI = /ttt/tags/test%26More,A,C%26A
ENV QUERY_STRING = -tags=test&More,A,C&A
CGI-Modul:
-tags=test&More%2CA%2CC=&A=
test
https://httpd.apache.org/docs/2.2/rewrite/flags.html#flag_bB (escape backreferences)
The [B] flag instructs RewriteRule to escape non-alphanumeric characters before applying the transformation.
mod_rewrite has to unescape URLs before mapping them, so backreferences will be unescaped at the time they are applied. Using the B flag, non-alphanumeric characters in backreferences will be escaped. For example, consider the rule:
RewriteRule ^search/(.*)$ /search.php?term=$1
Given a search term of 'x & y/z', a browser will encode it as 'x%20%26%20y%2Fz', making the request 'search/x%20%26%20y%2Fz'. Without the B flag, this rewrite rule will map to 'search.php?term=x & y/z', which isn't a valid URL, and so would be encoded as search.php?term=x%20&y%2Fz=, which is not what was intended.
With the B flag set on this same rule, the parameters are re-encoded before being passed on to the output URL, resulting in a correct mapping to /search.php?term=x%20%26%20y%2Fz.
Note that you may also need to set AllowEncodedSlashes to On to get this particular example to work, as httpd does not allow encoded slashes in URLs, and returns a 404 if it sees one.
This escaping is particularly necessary in a proxy situation, when the backend may break if presented with an unescaped URL.