Although this question is unrelated to the purpose of this forum, I will point out one thing (and provide you with a working example).
Based on your example: ${host} would assume the values [a1.com, a2.com, a3.com, ...]
Using proxy_pass www.mydomain.com/${host};
The resulting path should be like: www.mydomain.com/a1.com
Your request was for it to be like: mydomain.com/a1
The "www" is easily added or removed.
The ".com" is not as easy to remove; but it can be removed with a bit more cleverness:
Try: