Are square brackets permitted in URLs? Are square brackets permitted in URLs? apache apache

Are square brackets permitted in URLs?


RFC 3986 states

A host identified by an Internet Protocol literal address, version 6 [RFC3513] or later, is distinguished by enclosing the IP literal within square brackets ("[" and "]"). This is the only place where square bracket characters are allowed in the URI syntax.

So you should not be seeing such URI's in the wild in theory, as they should arrive encoded.


Square brackets [ and ] in URLs are not often supported.

Replace them by %5B and %5D:

  • Using a command line, the following example is based on bash and sed:

    url='http://example.com?day=[0-3][0-9]'encoded_url="$( sed 's/\[/%5B/g;s/]/%5D/g' <<< "$url")"
  • Using Java URLEncoder.encode(String s, String enc)

  • Using PHP rawurlencode() or urlencode()

    <?phpecho '<a href="http://example.com/day/',    rawurlencode('[0-3][0-9]'), '">';?>

    output:

    <a href="http://example.com/day/%5B0-3%5D%5B0-9%5D">

    or:

    <?php$query_string = 'day=' . urlencode('[0-3][0-9]') .                '&month=' . urlencode('[0-1][0-9]');echo '<a href="http://example.com?',      htmlentities($query_string), '">';?>
  • Using your favorite programming language... Please extend this answer by posting a comment or editing directly this answer to add the function you use from your programming language ;-)

For more details, see the RFC 3986 specifying the URL syntax. The Appendix A is about %-encoding in the query string (brackets as belonging to “gen-delims” to be %-encoded).


I know this question is a bit old, but I just wanted to note that PHP uses brackets to pass arrays in a URL.

http://www.example.com/foo.php?bar[]=1&bar[]=2&bar[]=3

In this case $_GET['bar'] will contain array(1, 2, 3).