URL Encode Forward Slash (/)
Learn how to URL encode the forward slash (/) as %2F. Understand when slashes must be encoded in URL parameters vs. path segments.
Character
/
Encoded
%2F
Detailed Explanation
The forward slash (/) is a reserved character in URLs that serves as the path segment separator. In URL paths, slashes define the hierarchical structure (e.g., /users/42/profile). When a slash appears inside a parameter value or within a single path segment as literal data, it must be encoded as %2F.
Percent-encoded form: %2F represents the forward slash (ASCII code 47, hexadecimal 0x2F). Encoding it prevents the URL parser from treating it as a path separator.
Context-dependent encoding: Whether you need to encode a slash depends entirely on where it appears in the URL:
- In a path: Slashes separate segments and should NOT be encoded (
/api/users/42) - In a parameter value: Slashes should be encoded (
?path=%2Fhome%2Fuser) - In a single path segment: Slashes must be encoded if the value is meant as one segment
JavaScript behavior:
encodeURIComponent("/home/user") // "%2Fhome%2Fuser"
encodeURI("/home/user") // "/home/user" (preserves slashes)
// Example: passing a file path as a query parameter
const filePath = "/var/log/app.log";
const url = `/api/view?file=${encodeURIComponent(filePath)}`;
// "/api/view?file=%2Fvar%2Flog%2Fapp.log"
Server-side considerations: Some web servers and frameworks handle %2F in path segments differently than literal /. Apache, for instance, may reject requests with %2F in the path by default (returning 404) unless AllowEncodedSlashes is enabled. Nginx passes them through but does not treat %2F as a path separator. This inconsistency can cause routing issues.
Common scenarios:
- Passing file system paths as URL parameters
- API endpoints that accept path-like identifiers (e.g.,
/repos/owner/name) - Date formats like
01/15/2026in query parameters - Referencing resource paths in redirect URLs
Pitfall: Be aware that some server frameworks automatically decode %2F before routing, which can create path traversal security vulnerabilities. If an application receives /files/..%2F..%2Fetc%2Fpasswd, a naive implementation might resolve this to /etc/passwd. Always validate and sanitize decoded paths on the server side.
Use Case
Passing file system paths or date strings containing slashes as URL query parameters, such as a log viewer API that accepts a file path parameter.