This is not a question that can be answered in a couple of lines.
In general, you will need to create a Dialplan that does that. The dialplan is specified in the file named “<b>extensions.conf</b>”
There is an excellent book called “Asterisk, the future of telephony”, which I would recommend reading.
You can download it from <a href=”http://svn.ninux.org/ninuxdeveloping/browser/sitoninux/trunk/AsteriskTFOT.pdf?rev=49″>here</a>
Chapters 5 and 6 explain how to create a dialplan.
Hope this helps.