in reply to how to use this -- HTTP_REFERER

It can work, but it's not reliable. Some browsers can block the referrer for privacy reasons.

Is there any reason why a user has to come to Mainpage.cgi from a.cgi or b.cgi? If it's because mainpage.cgi requires special CGI parameters, then perhaps you should fix mainpage.cgi to check input parameters and return an error if they are invalid.

You may consider another method: if you're saving state on the server and exchanging some kind of nonce or cookie, then perhaps log where the user was last and have mainpage.cgi check that.