简体   繁体   English

使用mod_rewrite重定向字符串的一部分

[英]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. 我需要在.htacess文件中使用下划线替换规则,并且301重定向查询字符串中包含空格(%20)或双精度空格(%2520)字符的任何部分。

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: 该参数需要在URL中更改并重定向到:

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. 不幸的是,我无法访问生成这些参数的PHP脚本,但我正在等待对其进行更改。

I would be grateful for a rule that I can place in my .htacess to do this. 我很高兴有一条规则可以放置在.htacess中,以实现此目的。

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. 在那种情况下,我不知道该怎么做,因为有时在mod_rewrite中匹配URL中的空格非常挑剔。

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). 说明:为了使301重定向正常工作,您需要将RewriteBase设置为包含.htaccess文件的目录(从Web浏览器中看到,相对于DocumentRoot)。

You must set RewriteCond to match the querystring, and choose the pattern to match. 您必须将RewriteCond设置为匹配查询字符串,然后选择要匹配的模式。

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. 在最后一行的替换模式中,$ 1是对RewriteRule模式的反向引用,而%1,%3是对RewriteCond模式的反向引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM