To do this you need to familiarize yourself with burrows and military alerts.
http://df.magmawiki.com/index.php/Burrows
The key is to make a burrow that is completely behind your defensive perimeter. Then, you can access the military alerts screen (Default: m - a) and set things up to restrict civilians to a particular burrow.
At that point, whenever you change the alert, when the sieges and ambushes come around, your civilians will not leave the safety of their burrow.
http://df.magmawiki.com/index.php/DF2010:Scheduling