Published on

URL encoding

Authors
  • avatar
    Name
    Alan Hu
    Twitter

URL encoding 是將特殊字串轉換為合法 URL 字串的過程,以確保正確傳輸和解析 URL。

含特殊符號的 query strings

https://example.com/search?filter=家電&傢俱&condition=折扣=50%

錯誤:整串 URL 進行 Encode

https%3A%2F%2Fexample.com%2Fsearch%3Ffilter%3D%E5%AE%B6%E9%9B%BB%26%E5%82%A2%E4%BF%B1%26condition%3D%E6%8A%98%E6%89%A3%3D50%25

正確:分別 Encode

# 針對 `家電&傢俱``折扣=50%` 分別進行 Encode
# 即可正確找到 filter、condition 的 query name 跟 value
https://example.com/search?filter=%E5%AE%B6%E9%9B%BB%26%E5%82%A2%E4%BF%B1&condition=%E6%8A%98%E6%89%A3%3D50%25

進階:嵌套式 url + 含特殊符號的 query strings

https://www.example.com/?url1=https://www.nested.com/?value1=I am the king!&cool=v&value2=GOO&a=OOD&url2=https://www.nested2.com/?value1=I am the queen!&cool=def&value2=GOO&a=OOD945

# url1
https://www.nested.com/?value1=I am the king!&cool=abc&value2=GOO&a=OOD
- `value1`=`I am the king!&cool=abc`
- `value2`=`GOO&a=OOD`

# url2
https://www.nested2.com/?value3=I am the queen!&cool=def&value4=GOO&a=OOD945
- `value3`=`I am the queen!&cool=def`
- `value4`=`GOO&a=OOD945`

嵌套 url 之 query string values 先分別 encode

# 先針對 value1, value2, value3, value4 分別 encode
- `value1`=`I%20am%20the%20king%21%26cool%3Dabc`
- `value2`=`GOO%26a%3DOOD`
- `value3`=`I%20am%20the%20queen%21%26cool%3Ddef`
- `value4`=`GOO%26a%3DOOD945`
# url1, url2 將 query strings 組裝後,再分別 encode
- `url1`=`https%3A%2F%2Fwww.nested.com%2F%3Fvalue1%3DI%2520am%2520the%2520king%2521%2526cool%253Dabc%26value2%3DGOO%2526a%253DOOD`
- `url2`=`https%3A%2F%2Fwww.nested2.com%2F%3Fvalue3%3DI%2520am%2520the%2520queen%2521%2526cool%253Ddef%26value4%3DGOO%2526a%253DOOD945`
# 將所有部分組合
# 即可得到所有嵌套欄位都有辦法正確解析的完整 url
https://www.example.com/?url1=https%3A%2F%2Fwww.nested.com%2F%3Fvalue1%3DI%2520am%2520the%2520king%2521%2526cool%253Dabc%26value2%3DGOO%2526a%253DOOD&url2=https%3A%2F%2Fwww.nested2.com%2F%3Fvalue3%3DI%2520am%2520the%2520queen%2521%2526cool%253Ddef%26value4%3DGOO%2526a%253DOOD945