46

I have some links in a page which only need to change the querystring portion of the current URL.

E.g. the current page is:

http://demo.com/bigreport?page=13

and I want to link to

http://demo.com/bigreport?page=14

Can I use <a href="?page=14">Next</a> as a relative link for this?

I was surprised to find it works in Chrome. I've never seen it documented or mentioned anywhere, so I'm keen to know if anyone uses this, and if there is wider browser support.

1
  • Great spot Ross, this technique makes certain annoying little problems much less annoying.
    – chim
    Feb 24, 2015 at 16:38

2 Answers 2

58

Further research reveals that <a href="?page=14">Next</a> is a valid relative URL.

It's documented as part of WHATWG's URL spec http://url.spec.whatwg.org/#relative-state

The new URL will inherit the base URL's scheme, host, port and path.

Tested to work on:

  • Chrome
  • IE 7
2
  • 2
    Note: Doesn't work if you have <base href="/"> in your <head> (figured out after a lot of head scratching) Feb 3, 2021 at 7:11
  • Note: this was nonstandard from 1998 to 2005 (broken in RFC 2396, fixed in RFC 3986), so it wouldn't surprise me if different browsers handled it differently during that time, and even for some time afterward. That may account for your not being familiar with it. (Alternatively, the fact that it was broken by RFC 2396 may reflect that it was already uncommon/unfamiliar.)
    – ruakh
    Feb 11 at 0:06
10

<a href="?page14">Next</a> works because browsers interpret that as a relative URL. Similar to how linking images on your site might work <img src="logo.gif"/> Relative urls work this way (link is relative to the current page), you don't need to use the full absolute URL.

Browsers have been supporting this for long long time. People might not be aware of it because browser automatically handles it.

3
  • 3
    Thanks - I've seen URLs relative to the current path (foo/bar.html), host (/foo/bar.html), and even protocol (://demo.com/foo/bar.html), but never the query string, so I was keen to know if this is part of a standard and widely supported.
    – Ross McNab
    Mar 8, 2013 at 10:10
  • Query string no different from any URI.
    – Amy
    Mar 8, 2013 at 10:14
  • @RossMcNab, you meant //demo.com/foo/bar.html, without the colon, right?
    – ByteEater
    Jul 11 at 0:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.