You don't, at least not generally. You might find something for 3, but then there's a situation with 4 URLs, et cetera...
Detecting infinite loops is the Holy Grail of computer science - very tempting but nonexistent: You might implement some safeguards for a limited set of conditions, but...