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 “extensions.conf”
There is an excellent book called “Asterisk, the future of telephony”, which I would recommend reading.
You can download it from here.
Chapters 5 and 6 explain how to create a dialplan.
Hope this helps.