Is a URL allowed to contain a space?
Solution 1:
As per RFC 1738:
Unsafe:
Characters can be unsafe for a number of reasons. The space character is unsafe because significant spaces may disappear and insignificant spaces may be introduced when URLs are transcribed or typeset or subjected to the treatment of word-processing programs. The characters
"<"
and">"
are unsafe because they are used as the delimiters around URLs in free text; the quote mark ("""
) is used to delimit URLs in some systems. The character"#"
is unsafe and should always be encoded because it is used in World Wide Web and in other systems to delimit a URL from a fragment/anchor identifier that might follow it. The character"%"
is unsafe because it is used for encodings of other characters. Other characters are unsafe because gateways and other transport agents are known to sometimes modify such characters. These characters are"{"
,"}"
,"|"
,"\"
,"^"
,"~"
,"["
,"]"
, and"`"
.All unsafe characters must always be encoded within a URL. For example, the character
"#"
must be encoded within URLs even in systems that do not normally deal with fragment or anchor identifiers, so that if the URL is copied into another system that does use them, it will not be necessary to change the URL encoding.
Solution 2:
Why does it have to be encoded? A request looks like this:
GET /url HTTP/1.1
(Ignoring headers)
There are 3 fields separated by a white space. If you put a space in your url:
GET /url end_url HTTP/1.1
You know have 4 fields, the HTTP server will tell you it is an invalid request.
GET /url%20end_url HTTP/1.1
3 fields => valid
Note: in the query string (after ?), a space is usually encoded as a +
GET /url?var=foo+bar HTTP/1.1
rather than
GET /url?var=foo%20bar HTTP/1.1
Solution 3:
Shorter answer: no, you must encode a space; it is correct to encode a space as +
, but only in the query string; in the path you must use %20
.