I need a rule in my .htacess file to replace with an underscore and 301 redirect any part of a querystring that contains the space (%20) or the double space (%2520) character.
So, for example, if a querystring contains the following parameter
weight=re开发者_如何学运维ally%2520really%20heavy
The parameter needs to be changed in the URL and redirected to:
weight=really_really_heavy
I need this as a temporary measure; unfortunately I do not have access to the PHP script that produces these parameters but I am waiting for them to be changed.
I would be grateful for a rule that I can place in my .htacess to do this.
RewriteRule ^(.*)\ (.*)$ $1_$2 [N]
should do it (adjusting the options in the brackets to whatever suits you); it replaces the first space with an underscore, then repeats the rule until it doesn't match any more. Note that the backslash-space might not work; in that case, I don't know how to do it since matching spaces in URLs in mod_rewrite is very finicky sometimes.
Use this to match the query string:
RewriteEngine On
RewriteBase /path/to/this/directory
RewriteCond %{QUERY_STRING} ^(.*)(%20|%2520)(.*)$
RewriteRule ^(.+)$ $1?%1_%3 [N,R=301]
Explanation: For the 301 redirect to work, you need to set RewriteBase to the directory containing the .htaccess file (as seen from the web browser, relative to DocumentRoot).
You must set RewriteCond to match the querystring, and choose the pattern to match.
In the replacement pattern in the last line, $1 is a back reference to the RewriteRule pattern, and %1, %3 are back references to the RewriteCond pattern.
精彩评论