問題描述

允許 URI(特別是 HTTP URL) 包含一個或多個空格字符?如果一個 URL 必須編碼,+只是一個常見的慣例,還是一個合法的選擇?

特別地,有人可以指向一個 RFC,該 RFC 指示具有空格的 URL 必須被編碼?

動機的問題:雖然 beta-testing 是一個網站,但我注意到有些 URL 是用空格構建的。 Firefox 似乎做了正確的事情,這讓我很驚訝!但是我希望能夠將開發人員指向一個 RFC,以便他們覺得需要修復這些 URL 。

最佳解決方案

根據 RFC 1738

Unsafe:

Characters can be unsafe for a number of reasons. The space character is unsafe because significant spaces may disappear and insignificant spaces may be introduced when URLs are transcribed or typeset or subjected to the treatment of word-processing programs. The characters "<" and ">" are unsafe because they are used as the delimiters around URLs in free text; the quote mark (""") is used to delimit URLs in some systems. The character "#" is unsafe and should always be encoded because it is used in World Wide Web and in other systems to delimit a URL from a fragment/anchor identifier that might follow it. The character "%" is unsafe because it is used for encodings of other characters. Other characters are unsafe because gateways and other transport agents are known to sometimes modify such characters. These characters are "{", "}", "|", "", "^", "~", "[", "]", and "`".

All unsafe characters must always be encoded within a URL. For example, the character "#" must be encoded within URLs even in systems that do not normally deal with fragment or anchor identifiers, so that if the URL is copied into another system that does use them, it will not be necessary to change the URL encoding.

次佳解決方案

為什麼要編碼?請求如下所示:

GET /url HTTP/1.1
(Ignoring headers)

有三個字段由一個空白區隔開。如果你在你的網址上放一個空格:

GET /url end_url HTTP/1.1

你知道有 4 個字段,HTTP 服務器會告訴你這是一個無效的請求。

GET /url%20end_url HTTP/1.1

3 個字段=> 有效

注意:在查詢字符串 (之後) 中,空格通常被編碼為+

GET /url?var=foo+bar HTTP/1.1 

而不是

GET /url?var=foo%20bar HTTP/1.1 

第三種解決方案

較短的答案:不,你必須編碼一個空格; 將空格編碼為+是正確的,但僅在查詢字符串中; 在路徑中您必須使用%20

第四種方案

URL 在 RFC 3986 中定義,但其他 RFC 也是相關的,但 RFC 1738 已過時。

他們可能沒有空格,還有許多其他字符。由於這些禁止的字符通常需要以某種方式進行表示,所以通過將它們轉換為具有”%” 前綴的 ASCII 十六進制等價物,可以將它們編碼成 URL 。

大多數編程語言/平台提供了對 URL 進行編碼和解碼的功能,儘管它們可能無法正確遵守 RFC 標準。例如,我知道 PHP 沒有。

第五種方案

是的,空間通常編碼為”%20″ 。出於安全原因,傳遞給 URL 的任何參數都應進行編碼。

第六種方案

Can someone point to an RFC indicating that a URL with a space must be encoded?

URI,因此 URL 在 RFC 3986 中定義。

如果你看看在那裏定義的語法,你最終會注意到一個空格字符永遠不會成為一個語法合法的 URL 的一部分,因此術語 「具有空格的 URL」 本身就是矛盾的。

第七種方案

這是一個很棒的頁面,它顯示了使用多種不同技術編寫的東西。

http://andrewu.co.uk/tools/uriencoder/

回答你的問題我會説,應用程序替換將用於 URL 中的值的空格是相當普遍的。這樣做的原因通常是避免發生更難讀取百分比 (URI) 編碼。

查看有關 Percent-encoding 的維基百科文章。

第八種方案

URL 可以在其中具有空格,並且它們將在大多數瀏覽器中顯示為%20,但是瀏覽器編碼規則變化很大,我們不能依賴於瀏覽器如何顯示 URL 。

因此,您可以用 URL 中的空格字符替換您認為 URL 的任何字符更易於閲讀和 「漂亮」;)….. 所以一般首選的字符是”-“,”_”,”+” …. 但是這些都是不要強迫,所以你可以使用任何不應該在 URL 中的字符已經。

請避免使用%,&,},{,],[,/,>,< 作為 URL 空間字符替換,因為它們可能會在某些瀏覽器和平台上引起錯誤。

您可以看到 Stak 溢出本身使用’-‘ 字符作為空格 (%20) 替換。

有一個快樂的問題。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇