How to check if the user is visiting the site’s root url?

The easiest JavaScript method is:

var is_root = location.pathname == "https://stackoverflow.com/"; //Equals true if we're at the root

Even http://example.com/?foo=bar#hash will produce the right result, since the pathname excludes the query string and location hash.

Have a look:

http://anything-but-a-slash/                  Root
                           /?querystring      Root
                           /#hash             Root
                           /page              Not root

If you have index file(s) at your root folder, have a look at the following example:

var is_root =/^\/(?:|index\.aspx?)$/i.test(location.pathname);

The previous line is using a regular expression. Special characters have to be escaped, the /i postfix makes the pattern case-insensitive. If you want the case to match, omit the i flag.

The same regular expression presented graphically:

Regular expression visualization

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)