Answered by Shaykh Sohail Hanif, SunniPath Academy Teacher
Is it permissible for someone to pray three rakahs (fard) for maghrib behind someone who is praying two rakahs (sunna) for maghrib? What are the rules generally for praying behind someone when the imam and follower will be praying a different number of rakahs, either more or less than the imam?
In the Hanafi school one may not pray an obligatory prayer behind someone praying a supererogatory prayer. The scenario mentioned in the question is therefore not allowed and not valid. One may not even pray a different obligatory prayer than that of the imam meaning that one cannot pray asr for example behind an imam praying dhuhr.
When praying behind someone, one’s prayer must be identical to that of the imam’s. This means that the prayer must be the same and likewise the time must be the same.
One may not therefore pray a makeup of asr behind someone praying a current performance of asr. The only case in which one may prayer a prayer that is not identical to that of the imam is if one is praying a supererogatory prayer in which case one may follow the imam regardless of his prayer as long as the time is one in which one may offer a supererogatory prayer and the imam is not praying an odd number of rakats.
One may not therefore pray a supererogatory prayer behind an imam immediately after performing one’s fajr prayer as one may not pray a supererogatory prayer after fajr until sunrise. One also may not pray a supererogatory prayer behind someone praying maghrib as that has an odd number of rakats. (al-Hadiyya al-`Ala’iyya)
The attached answer mentions the times in which one may not pray.