186

I'm writing code that automatically generates HTML, and I want it to encode things properly.

Say I'm generating a link to the following URL:

http://www.google.com/search?rls=en&q=stack+overflow

I'm assuming that all attribute values should be HTML-encoded. (Please correct me if I'm wrong.) So that means if I'm putting the above URL into an anchor tag, I should encode the ampersand as &, like this:

<a href="http://www.google.com/search?rls=en&amp;q=stack+overflow">

Is that correct?

4

4 Answers 4

195

Yes, it is. HTML entities are parsed inside HTML attributes, and a stray & would create an ambiguity. That's why you should always write &amp; instead of just & inside all HTML attributes.

That said, only & and quotes need to be encoded. If you have special characters like é in your attribute, you don't need to encode those to satisfy the HTML parser.

It used to be the case that URLs needed special treatment with non-ASCII characters, like é. You had to encode those using percent-escapes, and in this case it would give %C3%A9, because they were defined by RFC 1738. However, RFC 1738 has been superseded by RFC 3986 (URIs, Uniform Resource Identifiers) and RFC 3987 (IRIs, Internationalized Resource Identifiers), on which the WhatWG based its work to define how browsers should behave when they see an URL with non-ASCII characters in it since HTML5. It's therefore now safe to include non-ASCII characters in URLs, percent-encoded or not.

10
  • 2
    You can also encode spaces as "+" rather than %20 - which makes the URL easier to read.
    – NickG
    Aug 30, 2013 at 14:13
  • 3
    + isn't respected in mailto links in the native iPhone mail client currently, for what it's worth.
    – Ryan Olson
    Oct 8, 2013 at 20:17
  • 1
    é still needs encoding: stackoverflow.com/questions/2742852/unicode-characters-in-urls
    – lulalala
    Jan 21, 2014 at 4:03
  • 1
    @lulalala, I'd be curious to hear your case on that. I'm a Francophone and have been using French characters (including é) in a handful of URLs and I haven't had issues with it, assuming the web page had the correct encoding, of course. Here's one, and you can check the source to verify that Stack Overflow hasn't encoded it: fr.wikipedia.org/wiki/Allégorie_de_la_caverne
    – zneak
    Jan 21, 2014 at 7:16
  • 4
    I would add (as I just fell into this mistake) that if you are relying on a template engine you should check if that takes automatically care of escaping HTML entities or not. In my case Twig was doing that, and I was wrongly double-escaping writing &amp; into tag attribute instead of using directly &. Jan 26, 2015 at 10:00
28

By current official HTML recommendations, the ampersand must be escaped e.g. as &amp; in contexts like this. However, browsers do not require it, and the HTML5 CR proposes to make this a rule, so that special rules apply in attribute values. Current HTML5 validators are outdated in this respect (see bug report with comments).

It will remain possible to escape ampersands in attribute values, but apart from validation with current tools, there is no practical need to escape them in href values (and there is a small risk of making mistakes if you start escaping them).

6
  • 4
    XHTML (real XHTML sent as application/xhtml+xml) will most likely always require it, though.
    – zneak
    Nov 25, 2013 at 19:07
  • 5
    One caveat to this change, which is still being discussed, debated, and misunderstood, is that the & is supposed to be ok now, so long as it is "unambiguous". One obvious way to make the ampersand ambiguous is to follow it first with non-space characters and then a semicolon. That ampersand is now ambiguous, and will cause a parse error.
    – matty
    Aug 10, 2015 at 0:12
  • As Jukka said, there is certainly a risk to encoding all the ampersands, so consider how likely it is that one of your href urls contains a semicolon. Rather unlikely, as I'm not sure I've ever seen a url with a semicolon. Not that it can't be done. So practically speaking, I don't think it's likely that our use of & will be ambiguous. Therefore, we continue to use it unencoded in href attributes.
    – matty
    Aug 10, 2015 at 0:13
  • The whole reason the escaping is necessary is precisely because of the possibility of an ambiguity. This particular issue might not be introducing XSS attack vectors, bad rendering, or any affect at all 99.99% of the time, but that isn't a reason not to bother. Doing escaping correctly is hard and there's always the possibility of making mistakes.
    – Phil
    Oct 14, 2016 at 20:54
  • Perhaps it is time for an update? (But without "Edit:", "Update:", or similar - the answer should appear as if it was written today.) Nov 10, 2021 at 2:31
8

You have two standards concerning URLs in links (<a href).

The first standard is RFC 1866 (HTML 2.0) where in "3.2.1. Data Characters" you can read the characters which need to be escaped when used as the value for an HTML attribute. (Attributes themselves do not allow special characters at all, e.g. <a hr&ef="http://... is not allowed, nor is <a hr&amp;ef="http://....)

Later this has gone into the HTML 4 standard, the characters you need to escape are:

<   to   &lt;
>   to   &gt;
&   to   &amp;
"   to   &quote;
'   to   &apos;

The other standard is RFC 3986 "Generic URI standard", where URLs are handled (this happens when the browser is about to follow a link because the user clicked on the HTML element).

reserved    = gen-delims / sub-delims

gen-delims  = ":" / "/" / "?" / "#" / "[" / "]" / "@"

sub-delims  = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="

It is important to escape those characters so the client knows whether they represent data or a delimiter.

Example unescaped:

https://example.com/?user=test&password&te&st&goto=https://google.com

Example, a fully legitimate URL

https://example.com/?user=test&password&te%26st&goto=https%3A%2F%2Fgoogle.com

Example fully legitimate URL in the value of an HTML attribute:

https://example.com/?user=test&amp;password&amp;te%26st&amp;goto=https%3A%2F%2Fgoogle.com

Also important scenarios:

  • JavaScript code as a value:

    <img src="..." onclick="window.location.href = &quot;https://example.com/?user=test&amp;password&amp;te%26st&amp;goto=https%3A%2F%2Fgoogle.com&quot;;">...</a> (Yes, ;; is correct.)

  • JSON as a value:

    <a href="..." data-analytics="{&quot;event&quot;: &quot;click&quot;}">...</a>

  • Escaped things inside escaped things, double encoding, URL inside URL inside parameter, etc,...

    http://x.com/?passwordUrl=http%3A%2F%2Fy.com%2F%3Fuser%3Dtest&amp;password=&quot;&quot;123

I am posting a new answer because I find zneak's answer does not have enough examples, does not show HTML and URI handling as different aspects and standards and has some minor things missing.

3

Yes, you should convert & to &amp;.

This HTML validator tool by W3C is helpful for questions like this. It will tell you the errors and warnings for a particular page.

2
  • 2
    I'm not sure that the W3C validator detects this (unescaped & in a href) as an error.
    – ChrisW
    Jun 13, 2016 at 8:25
  • 12
    Currently, the W3C validator accepts unescaped & as valid. Does it mean that the standard has changed and encoding is no longer required? (making most answers here outdated)? If so, does this apply only to href or any attribute?
    – matteo
    Oct 5, 2017 at 17:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.