Matt
Matt

Reputation: 345

Redirect part of a string with mod_rewrite

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=really%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.

Upvotes: 1

Views: 669

Answers (2)

Jakob Egger
Jakob Egger

Reputation: 12041

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.

Upvotes: 1

Venge
Venge

Reputation: 2437

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.

Upvotes: 2

Related Questions