webextension:为什么浏览器向请求的 URL 添加尾部斜杠?
webextension: Why does the browser add a trailing slash to the requested URL?
当我向 http://www.example.com
发出请求时,为什么我在 webRequest.onBeforeRequestListener 中看到 http://www.example.com/
?
例如:
chrome.webRequest.onBeforeRequest.addListener(
details => console.log('Sending request to', details.url),
{ urls: ['<all_urls>'] });
fetch('http://www.example.com');
将打印
Sending request to http://www.example.com/
这与网络请求监视器中显示的请求URL一致。例如,如果我将其转换为 curl 命令,则请求如下所示:
curl 'http://www.example.com/' -H 'Accept: */*' -H 'Connection: keep-alive'
-H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.9'
-H 'User-Agent: ...' --compressed
因此,发出的原始请求是 http://www.example.com/
而不是 http://www.example.com
。该决定一定是在浏览器中做出的,而不是由服务器做出的。
使用 XMLHttpRequest
而不是 fetch
时也会发生相同的行为。在我的示例中,我使用了 Chrome,但在 Firefox 上它是相同的。
问题:
- 为什么浏览器会自动更改它?其他 URL 也会发生这种情况。根据我的理解,添加尾部斜线通常会起作用,但总的来说,这是一个重大变化。
- 如果我想在
onBeforeRequest
侦听器中针对特定 URL 的当前请求进行过滤,您如何可靠地匹配它?例如,仅检查 URL 是否相同将失败。
- 在浏览器中是否有更多需要注意的重写 URL 规则?
想想,我找到了。浏览器正在修复无效的 URL.
引用 Wikipedia,一个 URL 看起来像这样:
scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
The path must begin with a single slash (/) if an authority part was present, and may also if one was not, but must not begin with a double slash. The path is always defined, though the defined path may be empty (zero length), therefore no trailing slash.
http://example.com
有一个权限部分(在这个例子中,架构加上主机名:http://example.com
),但是路径是空的。根据规范,路径必须以 /
开头,因此浏览器通过将空路径替换为 /
来修复它。
如果使用有效的URL代替,如http://example.com/abc
,则不需要修改。
当我向 http://www.example.com
发出请求时,为什么我在 webRequest.onBeforeRequestListener 中看到 http://www.example.com/
?
例如:
chrome.webRequest.onBeforeRequest.addListener(
details => console.log('Sending request to', details.url),
{ urls: ['<all_urls>'] });
fetch('http://www.example.com');
将打印
Sending request to http://www.example.com/
这与网络请求监视器中显示的请求URL一致。例如,如果我将其转换为 curl 命令,则请求如下所示:
curl 'http://www.example.com/' -H 'Accept: */*' -H 'Connection: keep-alive'
-H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.9'
-H 'User-Agent: ...' --compressed
因此,发出的原始请求是 http://www.example.com/
而不是 http://www.example.com
。该决定一定是在浏览器中做出的,而不是由服务器做出的。
使用 XMLHttpRequest
而不是 fetch
时也会发生相同的行为。在我的示例中,我使用了 Chrome,但在 Firefox 上它是相同的。
问题:
- 为什么浏览器会自动更改它?其他 URL 也会发生这种情况。根据我的理解,添加尾部斜线通常会起作用,但总的来说,这是一个重大变化。
- 如果我想在
onBeforeRequest
侦听器中针对特定 URL 的当前请求进行过滤,您如何可靠地匹配它?例如,仅检查 URL 是否相同将失败。 - 在浏览器中是否有更多需要注意的重写 URL 规则?
想想,我找到了。浏览器正在修复无效的 URL.
引用 Wikipedia,一个 URL 看起来像这样:
scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
The path must begin with a single slash (/) if an authority part was present, and may also if one was not, but must not begin with a double slash. The path is always defined, though the defined path may be empty (zero length), therefore no trailing slash.
http://example.com
有一个权限部分(在这个例子中,架构加上主机名:http://example.com
),但是路径是空的。根据规范,路径必须以 /
开头,因此浏览器通过将空路径替换为 /
来修复它。
如果使用有效的URL代替,如http://example.com/abc
,则不需要修改。