URL エンコーディング vs HTML エンコーディング
URL のパーセントエンコーディングと HTML のエンティティエンコーディングの違いと、それぞれを使うべき場面を理解します。
问题
ユーザー入力を HTML コンテンツと URL の両方に表示する Web ページを作っており、どこにどのエンコーディングを適用すべきかを知る必要があります。
前提条件
- HTML の基礎知識
- URL 構造の基礎知識
ステップ
-
1. Understand the threat contexts
URL encoding (percent-encoding) protects query strings from misinterpretation. HTML encoding (entity encoding) protects page content from XSS by neutralizing characters like <, >, and &. They solve different problems in different contexts.
入力<script>alert(1)</script>输出HTML: <script>alert(1)</script> -
2. Apply the correct encoding per context
When placing user data inside HTML text, use HTML entity encoding. When placing user data inside a URL attribute (href, src), use URL encoding. For data inside a JavaScript string literal, use JavaScript string escaping.
入力O'Brien输出HTML: O'Brien | URL: O%27Brien -
3. Test both paths
Render the page and inspect the DOM. Confirm that no raw < or > appears in HTML and that the URL resolves correctly. Automated scanners can verify that no XSS vector remains.
入力user input in both contexts输出no injection possible
期待される結果
ユーザー入力が、XSS を許したりリンクを壊したりすることなく、HTML コンテンツと URL 属性の両方で安全に描画されること。
よくあるエラー
- Using URL encoding for HTML content
- URL encoding does not neutralize < and > for HTML. Always use HTML entity encoding for content displayed in the page.
- Forgetting to encode the ampersand in HTML attributes
- Encode & as & in HTML attribute values to avoid confusing the parser with entity references.
トラブルシューティング指引
- If the page shows literal < instead of <, you double-encoded. Decode once and re-encode only for the correct context.
- Use a framework's built-in escaping rather than manual encoding to avoid context mismatches.
セキュリティ上の制限
- Encoding is context-specific. Applying the wrong encoding leaves XSS or injection vulnerabilities open.