URL Encoding: Why Spaces Become %20
Learn how percent-encoding works, which characters need it, when a plus means a space, and how to avoid double encoding.
Key takeaways
- Percent-encoding writes a byte as
%plus two hexadecimal digits. - Reserved characters such as
?,&,#and/must be encoded when they're meant as plain data. - Non-English characters are normally converted to UTF-8 bytes first, then each byte is encoded.
- A
+means a space in form-encoded data, but not generally elsewhere in a URL. - Encode each piece once, with a library, before assembling the address.
A web address can safely contain only a limited set of characters. Anything else is written as a percent sign followed by two hexadecimal digits giving a byte's value. A space is byte 32, which is 20 in hexadecimal, so it becomes %20.
This is called percent-encoding, or URL encoding. It also protects characters that have a special job in an address, so that & inside a search term isn't mistaken for the divider between two parameters.
The structure being protected
A URL has parts separated by punctuation:
https://www.example.com/docs/guide?search=cables&page=2#setup The scheme ends at :, the host follows //, the path uses /, the query starts at ? with pairs joined by & and =, and the fragment starts at #. Each part is described in URL anatomy.
Now suppose someone searches for salt & pepper #1. Pasted in raw, the & would start a new parameter and the # would start a fragment, which the browser doesn't even send to the server. Encoded, the value stays whole:
?search=salt%20%26%20pepper%20%231 Reserved and unreserved characters
RFC 3986 sorts characters into groups.
| Group | Characters | Treatment |
|---|---|---|
| Unreserved | Letters, digits, - . _ ~ | Never need encoding |
| General delimiters | : / ? # [ ] @ | Structure; encode when used as data |
| Sub-delimiters | ! $ & ' ( ) * + , ; = | May have meaning; encode when in doubt in values |
| The percent sign | % | Encode as %25 when literal |
| Everything else | Space, quotes, < >, non-ASCII | Encode |
Whether a reserved character must be encoded depends on where it is. A / separates path segments, but inside a query value it's usually harmless. When you're inserting a value you didn't write, encoding all reserved characters is the safe choice.
Common codes
| Character | Encoded |
|---|---|
| space | %20 |
! | %21 |
# | %23 |
% | %25 |
& | %26 |
+ | %2B |
/ | %2F |
= | %3D |
? | %3F |
@ | %40 |
Hex digits may be upper or lower case; uppercase is preferred.
Beyond English letters
A percent sequence represents one byte, and characters outside ASCII take several bytes. Modern web practice converts text to UTF-8 and then encodes each byte. é becomes %C3%A9, and the euro sign becomes %E2%82%AC.
Your browser's address bar often shows the readable form while sending the encoded one, which is why copying an address sometimes produces a long string of percent signs. If decoding yields odd pairs such as é, the bytes were interpreted with the wrong encoding; see ASCII, Unicode and UTF-8.
Domain names follow a different rule. Non-ASCII labels are converted with Punycode into names beginning xn--, described in internationalized domain names.
Plus signs and forms
When a web form is submitted in the application/x-www-form-urlencoded format, spaces are written as +. A literal plus is then %2B. The query string of a form submitted with GET follows the same convention.
In a path, a + is just a plus. This mismatch causes real bugs: an email address such as [email protected] placed unencoded in a query can arrive as sam [email protected]. Encode it as sam%2Bnews%40example.com.
Encoding correctly in code
Let a library do it, and encode each component separately.
JavaScript:
const q = "salt & pepper #1";
encodeURIComponent(q); // salt%20%26%20pepper%20%231
const u = new URL("https://www.example.com/search");
u.searchParams.set("q", q); // form style, spaces as + encodeURIComponent is for a single value or path segment. encodeURI is for an already assembled address and deliberately leaves delimiters alone, so it won't protect an & inside a value.
Python:
from urllib.parse import quote, urlencode
quote("a b/c", safe="") # a%20b%2Fc
urlencode({"q": "salt & pepper"}) # q=salt+%26+pepper With curl in Bash, let it encode a query value for you:
curl -G https://www.example.com/search --data-urlencode "q=salt & pepper" More options appear in using curl.
Double encoding
Encoding an already encoded string turns %20 into %2520, because the % itself becomes %25. If you see %25 followed by two digits, something encoded twice.
Decode exactly once, too. Web frameworks usually decode query parameters for you, so decoding again can corrupt legitimate percent signs.
A URL inside a URL
Sign-in pages, redirectors and sharing buttons often carry one address as a parameter of another. The inner address has its own ?, & and =, so it must be encoded as a single value:
https://www.example.com/login?next=%2Fsearch%3Fq%3Dcables%26page%3D2 Decoded once, next is /search?q=cables&page=2. Without encoding, page=2 would belong to the login page, and the visitor would land on the wrong results.
Treat such parameters with care on the server. If your site redirects to whatever address arrives, someone can send out a link on your trusted domain that bounces to a hostile page. This is called an open redirect. Accept only relative paths on your own site, or compare the destination against a fixed list, and perform the check after decoding.
Where else percent signs matter
Some tools treat the percent sign specially for their own reasons. In a Windows batch file, % marks variables, so a literal encoded address may need each percent sign doubled. In a scheduled task line on many Linux systems, an unescaped % in a cron entry is read as a newline. In both cases the address is correct and the surrounding tool is altering it.
Shells cause the other classic failure. An unquoted & in Bash sends the command to the background, cutting the URL in two. Wrap addresses in quotes:
curl "https://www.example.com/search?q=cables&page=2" Copying from word processors and chat apps can add a trailing period, closing bracket or invisible character to a link. If a pasted address fails but looks right, look at its very end, and decode it to see whether an unexpected character has been encoded into it.
Servers and logs
Access logs usually record the request path as received, still encoded. Decode a copy when you're investigating, and search for both forms. A 400 Bad Request often points to a stray % that isn't followed by two hex digits, such as a literal "50%" typed into a link; write it as 50%25.
Web servers and frameworks differ in how they treat %2F in a path. Some decode it into a real slash, some refuse the request, and some pass it through. If an identifier can contain slashes, it's usually easier to put it in a query parameter than to depend on that behavior. Reading server logs explains the other fields you'll see beside each address.
Length and large values
Encoding makes text longer. One byte becomes three characters, and a single Chinese character, at three UTF-8 bytes, becomes nine. Browsers, servers and proxies each limit how long an address may be, and those limits differ. When you need to send a long document or a big set of filters, put it in a request body instead of the query string. A short identifier that points to saved settings on the server is another option, and it keeps shared links tidy.
Safety notes
Encoding makes characters travel correctly; it doesn't make input trustworthy. After decoding, a value can contain anything. Validate it, use parameterized database queries and escape output for HTML, as described in injection and scripting flaws.
Servers must also check file paths after decoding, never before, because encoded dots and slashes can disguise an attempt to reach other directories. Proxies and applications that decode differently can disagree about which resource a request names, so keep that handling consistent.
Encoding provides no secrecy either. Anything in a URL can end up in browser history, server logs and referrer information. Keep passwords and tokens out of addresses.
Readable addresses
For pages you publish, avoid needing encoding in the first place. Use lowercase words separated by hyphens, as in /guides/url-encoding. File names with spaces work, but they turn into links that are awkward to read and easy to break when pasted into plain text, where many programs stop the link at the first space. Brackets and trailing punctuation cause similar trouble, since the program guessing where a link ends may include or drop them.
When you add campaign tags, as in UTM parameters, keep values short and free of spaces and ampersands. If you rename existing pages to tidy their addresses, redirect the old ones so saved links keep working.
Inspecting a long address
To see what an encoded link really contains, paste it into a URL encoder and inspector or edit its parts in a query parameter editor. Be cautious with links from unknown senders: reading the decoded text is safe, but visiting it may not be. Check the host name carefully, since encoded text later in the address can be used to distract from where the link actually goes. Remove any session or reset tokens before sharing an address with someone else.