URL encoding is easy to get wrong when a value contains spaces, slashes, ampersands, plus signs, Unicode, or other reserved characters. This reference explains how percent encoding works, when to encode a complete URL versus one parameter, and how to construct and debug query strings safely in JavaScript, Python, PHP, and shell scripts.
Overview
A URL has several distinct parts, and each part follows different encoding rules. A typical address may contain a scheme, host, path, query string, and fragment:
https://example.test/products/blue-shirt?color=navy&sort=price#reviews
- Path: identifies a resource, such as
/products/blue-shirt. - Query string: carries parameters after
?, with name-value pairs separated by&. - Fragment: identifies a location within the returned resource after
#. Browsers generally process it locally rather than sending it as part of an HTTP request.
URL encoding, also called percent encoding, represents a byte with a percent sign followed by two hexadecimal digits. For example, a space can become %20, an ampersand can become %26, and a plus sign can become %2B. The important rule is to encode a value according to the URL component where it will be used—not to encode an entire URL indiscriminately.
For query string parameters, the safest general approach is to give a URL library the raw parameter values and let it serialize them. Manual string concatenation makes it easy for a value such as R&D to be mistaken for two parameters or for a literal plus sign to be mistaken for a space.
How to compare options
Before choosing an encoder or library function, identify three things: the component being built, the format expected by the receiving system, and where decoding will occur.
- Choose the component. A path segment, query parameter value, complete URL, form body, and fragment are related but not interchangeable inputs.
- Prefer structured APIs. URL builders and query-string serializers preserve separators such as
?,&, and=while escaping those characters when they occur inside values. - Define the contract. Confirm whether the server expects a repeated parameter, a comma-separated list, a JSON value, or form-style encoding. Encoding cannot correct an API contract that is ambiguous.
- Decode once at the boundary. The component that parses the request should decode it according to the format it received. Application code should avoid repeatedly decoding already-normalized values.
- Test round trips. Use values containing spaces,
&,+,/, percent signs, non-ASCII characters, and an empty string. Compare the parsed value with the original value, not just the visible URL.
There is no single “encode everything” function that is correct for every situation. A function designed for a complete URI may leave delimiters meaningful, while a component encoder must escape those same characters if they belong to the data.
Feature-by-feature breakdown
Characters worth testing
| Input | Common percent-encoded form | Why it matters |
|---|---|---|
| Space | %20 | Some form encoders use + instead, so do not assume the two formats are interchangeable. |
/ | %2F | Usually meaningful in a path; encode it when it is data inside one path segment or parameter. |
& | %26 | Must be escaped inside a value or it can start another query parameter. |
+ | %2B | Important because form-style query parsing may interpret an unescaped plus as a space. |
? | %3F | Has structural meaning before the query; encode it when it is data. |
# | %23 | Starts a fragment when unescaped and therefore must be encoded inside a value. |
| Unicode text | UTF-8 bytes represented with percent escapes | Use a library that applies the expected character encoding instead of writing byte conversions manually. |
% | %25 | Prevents an existing percent sign from being mistaken for the start of an escape sequence. |
JavaScript
Use URLSearchParams when constructing query parameters. It handles separators and repeated keys without requiring manual concatenation:
const params = new URLSearchParams({
q: 'R&D + design',
page: '2'
});
const url = `https://example.test/search?${params}`;
For one value that will occupy one component, encodeURIComponent() is the usual choice:
const pathSegment = encodeURIComponent('reports/2026');
const queryValue = encodeURIComponent('R&D + design');
encodeURI() is intended for a URI whose delimiters should remain meaningful. It is not a replacement for encoding an individual query value. When parsing, use URL, URLSearchParams, and their accessors rather than splitting a raw query string by every ampersand.
Python
The standard library separates query construction from component quoting. urlencode() is useful for query parameters, while quote() is appropriate when you are deliberately encoding a path component:
from urllib.parse import urlencode, quote
query = urlencode({
'q': 'R&D + design',
'page': 2,
})
url = 'https://example.test/search?' + query
segment = quote('reports/2026', safe='')
When a parameter can occur more than once, pass a sequence of pairs and enable the option that preserves multiple values. This is clearer than packing a list into a comma-separated string unless the API explicitly requires commas.
PHP
Use http_build_query() for a query string and rawurlencode() for a path segment or other value where spaces should use percent encoding:
$query = http_build_query([
'q' => 'R&D + design',
'page' => 2,
]);
$url = 'https://example.test/search?' . $query;
$segment = rawurlencode('reports/2026');
Do not apply rawurlencode() to a complete URL containing its scheme and separators. That would turn structural characters into data and produce an unusable address.
Shell and command-line requests
Shell commands have a second concern: quoting for the shell itself. Put a complete URL in single quotes when it contains ampersands, dollar signs, or other shell metacharacters. For generated values, use a language or command-line tool that can encode query parameters rather than relying on ad hoc substitutions.
curl 'https://example.test/search?q=R%26D%20%2B%20design&page=2'
For API debugging, inspect the final request URL, headers, and body separately. A useful next step is the API debugging workflow for HTTP errors, headers, CORS, and request bodies.
Query strings versus form data
Query strings and application/x-www-form-urlencoded form bodies share conventions, including the common use of + for a space in form-style serialization. That does not mean a literal plus should remain unescaped. If the data is a mathematical expression such as C++, encode the plus signs or use a serializer that does so for you. JSON request bodies follow different rules: JSON escaping and URL percent encoding are separate operations.
Best fit by scenario
- Adding search filters to a link: use a URL builder or query serializer. Encode each name and value, then join parameters through the library rather than assembling
&manually. - Inserting user input into one path segment: use a component encoder with slash treated as data. Validate the resulting route as well, because encoding does not replace authorization or input validation.
- Building a path from multiple segments: encode each segment separately and join the encoded segments with literal slashes. Encoding the entire path can erase the distinction between separators and segment content.
- Preserving a redirect target: encode the target as the value of one parameter. A nested URL contains its own punctuation, so those characters must not be allowed to become punctuation in the outer URL.
- Creating an anchor link: keep the fragment identifier separate from the query. Encode fragment data as a fragment component and remember that it may not be visible to the server.
- Sending a form submission: use the framework's form serializer and confirm whether the endpoint expects form encoding, JSON, or multipart data.
If a URL contains complex filters, document the parameter format alongside the endpoint. For readable database-related workflows, consistent serialization is as useful as consistent SQL formatting; the SQL formatter and query style guide covers the related problem of making queries easier to inspect.
When to revisit
Revisit this reference whenever a request changes from a path parameter to a query parameter, a service changes its form or JSON contract, or a client library is upgraded. Browser and language APIs evolve, and framework wrappers may add their own serialization behavior. Verify the actual output after such changes rather than relying on the function name alone.
A practical troubleshooting workflow
- Capture the raw input. Record the intended value before any encoding, including its spaces, plus signs, percent signs, and Unicode characters.
- Identify each boundary. Mark the base URL, path segments, query names, query values, and fragment. Ask which layer owns each delimiter.
- Inspect the wire representation. Look for unexpected
%25, a literal+where a space was expected, unescaped&, or a fragment that never reached the server. - Check for double encoding. A value such as
%2Fbecoming%252Fusually indicates that an already encoded value was encoded again. Keep values decoded internally and encode only when constructing the outgoing component. - Decode at the correct layer. Determine whether the framework has already parsed query parameters. Decoding again can turn literal data into control characters or alter percent sequences.
- Test empty and repeated values. Confirm the difference between a missing parameter, an empty parameter, and multiple occurrences such as
tag=a&tag=b. - Retest the round trip. Send the request through the same client and server path used in production, then compare the received value with the original input.
Keep a small regression set containing hello world, R&D, C++, reports/2026, 100%, an empty string, and a non-ASCII value. Run it whenever routing, request libraries, middleware, or API contracts change. That simple check catches most URL encoding regressions before they become redirect, search, or integration bugs.