URL Encoding vs HTML Encoding
Understand 差集之间 percent-编码为 URLs 和 entity 编码为 HTML, 和当 到 use 每个.
问题
你是 building web page 该 displays 用户输入在 两者 HTML 内容和 URL, 和你 need 到知道哪个编码到 应用 where.
前置条件
- 基础 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
预期结果
User 输入是 安全 rendered 在两者 HTML 内容和 URL attributes 无 enabling XSS 或 breaking links.
常见错误
- 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.