是否应该在查询字符串中对 & 符号进行 URL 编码?

Should an ampersand be URL encoded in a query string?

例如,我经常看到这个 URL 出现。

https://ghbtns.com/github-btn.html?user=example&repo=card&type=watch&count=true

&& 还是 should/can 是 &

来自rfc3986

Reserved Characters
URIs include components and subcomponents that are delimited by characters in the "reserved" set. These characters are called "reserved" because they may (or may not) be defined as delimiters by the generic syntax, by each scheme-specific syntax, or by the implementation-specific syntax of a URI's dereferencing algorithm.
...

  reserved    = gen-delims / sub-delims

  gen-delims  = ":" / "/" / "?" / "#" / "[" / "]" / "@"

  sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
              / "*" / "+" / "," / ";" / "="

The purpose of reserved characters is to provide a set of delimiting characters that are distinguishable from other data within a URI. URIs that differ in the replacement of a reserved character with its corresponding percent-encoded octet are not equivalent. Percent-encoding a reserved character, or decoding a percent-encoded octet that corresponds to a reserved character, will change how the URI is interpreted by most applications.
...
URI producing applications should percent-encode data octets that correspond to characters in the reserved set unless these characters are specifically allowed by the URI scheme to represent data in that component. If a reserved character is found in a URI component and no delimiting role is known for that character, then it must be interpreted as representing the data octet corresponding to that character's encoding in US-ASCII.

因此,如果 URL 中的 & 是值的一部分并且 没有定界作用
这很简单PHP 使用 urlencode() 函数的代码片段:

<?php
    $query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
    echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?> 

&amp; 用于在 HTML.

中编码符号

例如,在超链接中:

<a href="/github-btn.html?user=example&amp;repo=card&amp;type=watch&amp;count=true">…</a>

(注意这个only changes the link, not the URL。URL还是/github-btn.html?user=example&repo=card&type=watch&count=true。)

虽然您可以在 HTML 中使用 &amp; 对每个 &(内容的一部分)进行编码,但您只需要对 ambiguous ampersands.