Proper URL forming with a query string and an anchor hashtag

PhpWordpressUrlStandardsUrl Fragment

Php Problem Overview


When both a query string and anchor tag (hash tag) are visible in a URL, what is the proper order for them to appear?

http://www.whatever.com?var=val#anchor

or

http://www.whatever.com#anchor?var=val

Is there any documentation on this?

The URLs are being handled by WordPress / PHP.

Php Solutions


Solution 1 - Php

?var=var#hash

Everything after # is client side.

Also, look into URL rewriting to get rid of ugly ?var=var.

Solution 2 - Php

? should come before the # as noted in RFC 3986:

relative-ref = relative-part [ "?" query ] [ "#" fragment ]

Taken from an answer over at Super User (Does an anchor tag come before the query string or after?):

Solution 3 - Php

Note that when the URL has both anchor tags (#) and query strings (?), the browser may ignore the query string and navigate to the anchor tag without reloading the page.

It may be necessary to submit the page using a

<form action='webpage.php?q=string#tag' method='GET or POST'>
    <input type='text' id='q' name='q' value='string'>
    <input type='submit' value='submit'>
</form>

rather than just a URL link

<a href='webpage.php?q=string#tag'>.

Solution 4 - Php

If the intention of using # is to denote a page fragment then - yes ? and then #.

If # is coming before ? and it is not to denote a page fragment (this can happen when # is part of authority (username and password)) it has to be encoded or you are in trouble. The same applies to any other special characters (:,@,...) that could give a different meaning to the URL.

Solution 5 - Php

You may place this JavaScript code in the common part of your site to force redirecting all incorrect requests to the analog with proper order:

<script>
    var p=location.hash.indexOf("?");
    if(p>=0){
        var goodLoc = location.href.replace(location.hash, "");
        location.replace(goodLoc + window.location.hash.substring(p) + window.location.hash.substring(0, p));
    }
</script>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanView Question on Stackoverflow
Solution 1 - PhpblitzmannView Answer on Stackoverflow
Solution 2 - PhpbillyView Answer on Stackoverflow
Solution 3 - PhpTeacher MichaelView Answer on Stackoverflow
Solution 4 - PhpMatas VaitkeviciusView Answer on Stackoverflow
Solution 5 - PhpЯраслаў ЖукView Answer on Stackoverflow