URL Path Encoding vs Query String Encoding

Learn the differences between URL path segment encoding and query string encoding. Understand which characters are safe in each context and why it matters.

Detailed Explanation

URL paths and query strings have different encoding rules because they serve different structural purposes. Characters that are safe in a path may need encoding in a query string, and vice versa. Understanding these differences is critical for building correct URLs.

URL anatomy:

https://example.com/path/segment?key=value&key2=value2#fragment
                    |-- path ---|--- query string -----|--frag--|

Path encoding rules:

  • Forward slashes / are segment separators (do not encode)
  • Colons : are allowed (but sometimes ambiguous)
  • @ is allowed in path segments
  • + is a literal plus sign, NOT a space
  • Each path segment should be individually encoded with encodeURIComponent(), then joined with /

Query string encoding rules:

  • & separates parameters (encode when in values)
  • = separates keys from values (encode when in values)
  • + represents a space (in form encoding)
  • ? is the query string delimiter (encode when in values)

JavaScript approach:

// Building a path with dynamic segments
const userName = "John Doe/Admin";
const pathSegment = encodeURIComponent(userName);
const path = `/users/${pathSegment}/profile`;
// "/users/John%20Doe%2FAdmin/profile"

// Building a query string
const params = new URLSearchParams({ user: "John Doe/Admin" });
const query = params.toString();
// "user=John+Doe%2FAdmin"

// Combining both
const fullUrl = `https://example.com${path}?${query}`;

Key differences summarized:

Character In Path In Query Value
Space %20 %20 or +
/ Separator (don't encode) %2F
+ Literal plus sign Space (form encoding) or %2B
? %3F Starts query (encode in values)
& Allowed Parameter separator (encode in values)
= Allowed Key-value separator (encode in values)
@ Allowed %40
: Allowed %3A

Common mistake: Using the same encoding function for both path and query components. For paths, you encode individual segments with encodeURIComponent() but preserve the / separators between segments. For query strings, you encode individual keys and values. Never encode the entire URL at once.

Pitfall: The + character behaves differently in paths and queries. In a path, /search/c++ contains a literal ++. In a query, ?lang=c++ is interpreted as lang=c (two spaces) under form encoding rules. If you want a literal + in a query value, always encode it as %2B.

Use Case

Building REST API URLs with dynamic path parameters and query filters, ensuring each component is encoded correctly for its position in the URL.

Try It — URL Encoder

Open full tool