简体   繁体   English

如何处理.htaccess规则中的&和/等特殊字符?

[英]How to handle special characters like & and / in .htaccess rules?

In my .htaccess file I have defined following rule, 在我的.htaccess文件中,我定义了以下规则,

RewriteRule ^([-0-9a-zA-Z]+) search.php?id=$1

The above rule works fine if I am browsing http://example.com/abcd I need to use the symbols & % - / in the url like: http://example.com/ab&cd 如果我在浏览http://example.com/abcd,我需要在网址中使用符号& % - / ,例如: http : //example.com/ab&cd,则上述规则适用

What changes have to be made to the rule for this to work? 要使规则生效,必须进行哪些更改?

No idea how that rule is working for you. 不知道该规则如何为您工作。 First, it loops. 首先,它循环。 Second, there is no capture groups for $2 and $3 , but it doesn't matter because $1 is always "search" anyways. 其次,没有用于$2$3捕获组,但这并不重要,因为无论如何$1始终是“搜索”。 I'm assuming you've pasted a partial snippet of a rule that you have that works. 我假设您粘贴了一条行之有效的规则的部分代码。

The reason why & , % , or / isn't being matched is because your regex says: &%/不匹配的原因是因为您的正则表达式说:

[-0-9a-zA-Z]+

which means: one or more letters, numbers, or a dash . 表示: 一个或多个字母,数字或破折号 So no & , % , or / . 所以没有&%/ So you can add those into the square brackets: 因此,您可以将其添加到方括号中:

RewriteRule ^([-0-9a-zA-Z/%&]+) search.php?id=$1&ff=$2&ffid=$3

However, keep in mind that the URI is decoded before any rules get applied. 但是,请记住,在应用任何规则之前都会对URI进行解码 This means if the URI looks like: 这意味着如果URI看起来像:

/foo%28bar

You don't need to match against % , because the URI gets decoded into: 您不需要与%匹配,因为URI被解码为:

/foo(bar

and you need to match against ( . A better option may to just match against every except dots: 并且需要与(匹配。一个更好的选择可能是与之外的所有其他点匹配:

RewriteRule ^([^.]+) search.php?id=$1&ff=$2&ffid=$3

or whatever you don't want in your match. 或您比赛中想要的任何东西。


Try: 尝试:

RewriteRule ^([^.]+)$ search.php?id=$1 [B]

The difference here is the $ to bound the match to the end of the URI, and the B flag ensures the & gets encoded. 此处的区别是将匹配项绑定到URI末尾的$B标志确保&被编码。

You need to URL encode 'ab&cd' using urlencode so that & gets turned into %26 . 您需要使用urlencode'ab&cd'进行编码,以使&变成%26

After this, in search.php you'll need to account for it and decode it, using urldecode . 此后,您需要在search.php中使用urldecode对其进行解释和解码。

Do the URL like this: 做这样的URL:

http://example.com/id/ff/ffid

and write your rule around that. 并写下您的规则。 Also, why do you need 3 ID parameters? 另外,为什么需要3个ID参数? Couldn't you just lookup the other 2 using the first one? 您不能只使用第一个查找其他两个吗?

用你的网址

RewriteRule ^directory/([^/.]+)$ /searchpage.php?search_keywords=$1  [L]

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

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