Skip to content
uencoder
TUTORIAL

URL Encoding vs HTML Encoding

Understand the difference between percent-encoding for URLs and entity encoding for HTML, and when to use each.

Problem

You are building a web page that displays user input in both HTML content and a URL, and you need to know which encoding to apply where.

Prerequisites

  • Basic HTML knowledge
  • Basic URL structure knowledge

Steps

  1. 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.

    Input
    <script>alert(1)</script>
    Output
    HTML: &lt;script&gt;alert(1)&lt;/script&gt;
  2. 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.

    Input
    O'Brien
    Output
    HTML: O&#39;Brien | URL: O%27Brien
  3. 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.

    Input
    user input in both contexts
    Output
    no injection possible

Expected result

User input is safely rendered in both HTML content and URL attributes without enabling XSS or breaking links.

Common errors

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 &amp; in HTML attribute values to avoid confusing the parser with entity references.

Troubleshooting

  • If the page shows literal &lt; 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.

Security limits

  • Encoding is context-specific. Applying the wrong encoding leaves XSS or injection vulnerabilities open.

Related tools

Related tasks

Ready to run it?

References