That script probably uses the HTTP_REFERER value.
That value contains the url of the previously visited page.
In your case,when you go to the index page, then link to a sub-page, the HTTP_REFERER contains the url of the index page. But when you click to a sub-sub-page, the REFERER contains the URL of the sub-page, which is not the index page, so access is denied.
Instead of checking for the index page, check only to see if the REFERER contains a page that is on your site or your domain.