特殊文字を URL エンコードする方法
URL でそのまま使えない文字をエンコードし、クエリ文字列内で正しく伝送できるようにします。
问题
URL にスペース、アンパサンドなどの特殊文字が含まれており、クエリ文字列の構造が壊れています。
前提条件
- URL 構造の基礎知識
- パーセントエンコーディングの理解
ステップ
-
1. Identify unsafe characters
Characters like space, &, =, ?, #, and + have special meaning in URLs. Leaving them unencoded will change how the server parses the query string. Review your input and flag every reserved or non-ASCII character.
入力name=John Doe & Co.输出unsafe: space, & -
2. Percent-encode each character
Replace each unsafe character with a percent sign followed by its two-digit UTF-8 hex byte. A space becomes %20, an ampersand becomes %26, and a non-ASCII character may produce multiple percent sequences.
入力name=John Doe & Co.输出name=John%20Doe%20%26%20Co. -
3. Verify the encoded URL
Paste the encoded URL into a browser or HTTP client. The server should receive the original string exactly. If any character is still raw, the encoding was incomplete.
入力name=John%20Doe%20%26%20Co.输出server receives: name=John Doe & Co.
期待される結果
標準準拠のサーバーならどれでも曖昧さなくパースできる、完全にパーセントエンコードされた URL。
よくあるエラー
- Encoding the entire URL including the scheme and host
- Only encode the query parameter values and path segments, not the protocol or domain.
- Double-encoding an already-encoded string
- Check for existing % sequences before encoding. Decode first if you need to re-encode.
トラブルシューティング指引
- If the server receives literal %20 instead of a space, the string was double-encoded.
- Use encodeURIComponent in JavaScript for query values, not encodeURI.
セキュリティ上の制限
- URL encoding prevents parsing errors but does not prevent injection. Validate and sanitize all input on the server side.