I need to convert the following where website url that user inputs ,

var1 is a wildcard set by user to login to his account details.  

<http://var1.domain.com/var2/var3>  

redirect to:  

<http://domain.com/master5.php?uid=var1&wid=var2&camid=var3>

and another rule i need is

var1.domain.com/var2/  

redirect to:  

domain.com/master5.php?uid=var1&wid=var2

if possible I need to cloak them too so user actually only see  

var1.domain.com/var2/var3