Is a URL allowed to contain a space?
Strictly speaking, URLs are not allowed to contain spaces. Spaces must be encoded using %20
or +
. Therefore, for "my file", you should input my%20file
or my+file
in a URL.
Example:
https://example.com/my%20file
https://example.com/my+file
Necessity of encoding spaces in URLs
Spaces can create ambiguities as they are interpreted as end-of-line characters in HTTP requests. To ensure your URLs are secure and unambiguous, it's therefore necessary to encode spaces. In the past, programmers lost many nights of sleep because of missing or misinterpreted spaces. Don't be one of them!
Alternatives to spaces im URL paths
When readability and SEO are on your checklist, dashes (-
) and underscores (_
) are the prime choice over %20
and +
. These replacements make URLs more legible and search-engine-friendly.
How modern browsers handle spaces
Modern browsers like Firefox got your back. They save you from sleepless nights by automatically encoding the spaces in a URL. However, not all browsers are your best friends, especially the older ones, which might make you long for the good old pen and paper days.
Standards: Then and now
Our dear old RFC 1738 has retired and RFC 3986 is now the new rule in town. It further enforces that forbidden characters should be percent-encoded. So, don't be a rebel and stick to the current standards. You might say, rules are meant to be broken, but trust me, not these ones!
PHP corner: Encoding spaces
When you walk on the PHP road, be extra careful with URL encoding. PHP relies heavily on accurate URL parsing, and any screw-up can send your whole application on a wild goose chase. Remember, being an Encoding Guru is not optional when dealing with backend technologies!
Encoding spaces in URL queries
While +
makes an appearance as a space in URL queries, don't mistake it for a Hollywood star. It is just another encoding mechanism, especially in form submissions to maintain data consistency. It's aptly like saying, "Why should %20
have all the fun?"
Was this article helpful?