very similarly to the way you assumed;
in your main.php file, wherever it detects whether the user is logged in or not, put something like this
<?php
if($logged_in == false){
header("Location:login.php?location=main.php");
}
?>
then in your login page after it authenticates, have something like this
<?
$location = $_GET[location];
if($location != ""){
header("Location:" . $location);
}
?>
good luck