Robert Lewandowski gave Bayern the lead but Dusan Tadic equalised.
Maximilian Wober was sent off for Ajax, with Bayern’s Thomas Muller dismissed for kicking Nicolas Tagliafico’s head.
Tadic then put Ajax ahead with an 82nd-minute penalty, but there were three goals to come. Lewandowski scored a spot-kick with Bayern’s Kingsley Coman netting before Niklas Sule’s own goal.
Lewandowski has scored 21 goals in as many games this season.
Bayern topped Group E with the victory, although Ajax would have overtaken them if they had held on to their 2-1 lead.
Elsewhere, Lyon qualified for the knockout stages with a 1-1 draw at Shakhtar Donetsk. The Ukrainian hosts knew a win would take them through and led thanks to Junior Moraes’ strike.
But Nabil Fekir’s curling effort took the French side through with one win – in their opener against group winners Manchester City – followed by five consecutive draws.
AEK Athens finished bottom of Group E on zero points thanks to Alex Grimaldo’s late winner for Benfica.
Juventus won Group H despite losing 2-1 at Young Boys. French veteran Guillaume Hoarau scored twice for the Swiss side before Paulo Dybala’s consolation.