Why does the percent sign in a URL cause an HTTP 400 Bad Request error?

21,762

Solution 1

Short answer

As per RFC 3986, a bare % character is not a valid URI syntax; it should be followed by two meaningful hexadecimal digits.

Long answer

The HTTP status code you got belongs to the 4xx class:

4xx: Client Error - The request contains bad syntax or cannot be fulfilled

Source: Hypertext Transfer Protocol (HTTP) Status Code Registry

In particular, code 400 is defined by the Internet Engineering Task Force (IETF) in RFC 2616:

10.4.1 400 Bad Request

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

Source: RFC 2616 - Hypertext Transfer Protocol -- HTTP/1.1

Quoting Wikipedia (bold emphasis mine):

The characters allowed in a URI are either reserved or unreserved (or a percent character as part of a percent-encoding).

Source: Percent-encoding - Percent-encoding in a URI

If you want to insert a literal % symbol, you need to use its percent-encoded representation: %25.

Further reading

Solution 2

The percent sign is for inserting a character that is normally not supported in the url. For example %20 is the same as a space.

Share:
21,762

Related videos on Youtube

iglvzx
Author by

iglvzx

Email: [email protected] Twitter: @iglvzx LinkedIn: israelgalvez Free Software Foundation Member #9943 Technical Support Hero. Developer behind GWhois.org - the most advanced Whois client in the world! Live, authoritative Whois lookups for domain names and IP addresses, DNS tools, and more!

Updated on September 18, 2022

Comments

  • iglvzx
    iglvzx over 1 year

    I stumbled upon this by accident when mistyping the URL for a web page in my web browser.

    Why does visiting http://example.com/% cause an HTTP 400 Bad Request error to be thrown? Is the server expecting something else after or before the percent sign?

    It seems to happen for Apache and Nginx servers.

  • Robotnik
    Robotnik almost 10 years
    And to insert a percent character itself, it's %25
  • Phil Perry
    Phil Perry almost 10 years
    A + is a shortcut way to encode a space. If you want a real plus sign, use its hex code, %2B.
  • Eden Townsend
    Eden Townsend almost 10 years
    + is the correct encoding for a space only within a query string. %20 is the correct encoding elsewhere within the url.
  • fiffy
    fiffy almost 7 years
    I don't get it. If I mask the '%' sign with '%25' the file will still not be served but an error 400 will be thrown in our scenario (Apache -> JKMount -> Tomcat)
  • Marco Marsala
    Marco Marsala over 4 years
    If you have the following RewriteRule RewriteRule (.*) xyz/$1 (where xyz is any folder name) in .htaccess, you should double-encode % as %2525.