如何编码“..”以便在 URL 路径中使用?

How to encode ".." for use in a URL path?

我正在尝试构建一个 URL 类似的东西:

var myUrl = '/path/to/api/' + encodeURIComponent(str);

但是,如果 str..,那么您的浏览器会自动截掉一个路径段,这样 URL 就会变成 /path/to,这不是我想要的。

我已经尝试将 .. 编码为 %2E%2E,但您的浏览器在发送请求之前仍会重新解释它。我能做些什么来让 actually/path/to/api/.. 的形式到达我的服务器?

我认为这不受支持,因为该行为会违反 RFC 3986

来自 Section 2.3. Unreserved Characters(强调我的):

Characters that are allowed in a URI but do not have a reserved purpose are called unreserved. These include uppercase and lowercase letters, decimal digits, hyphen, period, underscore, and tilde.

 unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"

URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent: they identify the same resource. However, URI comparison implementations do not always perform normalization prior to comparison (see Section 6). For consistency, percent-encoded octets in the ranges of ALPHA (%41-%5A and %61-%7A), DIGIT (%30-%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should not be created by URI producers and, when found in a URI, should be decoded to their corresponding unreserved characters by URI normalizers.

来自 Section 6.2.2.3. Path Segment Normalization(强调我的):

The complete path segments "." and ".." are intended only for use within relative references (Section 4.1) and are removed as part of the reference resolution process (Section 5.2). However, some deployed implementations incorrectly assume that reference resolution is not necessary when the reference is already a URI and thus fail to remove dot-segments when they occur in non-relative paths. URI normalizers should remove dot-segments by applying the remove_dot_segments algorithm to the path, as described in Section 5.2.4.):

既然有 ,除了错误,我们无能为力:

export function encodeUriComponent(str) {
    if(str === '.' || str === '..') {
        throw new Error(`Cannot URI-encode "${str}" per RFC 3986 §6.2.2.3`)
    }
    return encodeURIComponent(str);
}

我觉得这是一个比任意修改 URL 路径更好的选择,这正是我试图通过使用 encodeURIComponent.

来避免的

我实际上已经通过对文本进行双重编码,然后在服务器后端对其进行取消编码来完成类似的操作。但是,我的是查询参数,而不是路径的一部分。

PS。这个写在我的phone上了,后面会补上例子。