The result is enough for Ajax to qualify for the Europa League as Manchester City lost 1-0 at Borussia Dortmund in the other game in the group.
© AP Photos
The hosts thought that they had scored as early in seventh minute when a slick move between Cristiano Ronaldo, Kaka and Karim Benzema saw the Frenchman slide home from inside the box, but it was ruled out for offside.
Four minutes later Madrid were unlucky not to break ahead, as Fabio Coentrao's shot from just inside the Ajax penalty box came off the post.
Madrid, though, not have to wait long as Ronaldo put them 1-0 up in the 13th minute at the Santiago Bernabeu.
Luka Modric found Benzema with a ball over the top of the Ajax defence and the French striker then slipped a pass to Ronaldo, who smashed home with ease.
Benzema himself almost doubled Madrid's advantage just minutes later with a quick strike on goal, but Ajax goalkeeper Kenneth Vermeer managed to pull off a save.
Madrid eventually made it 2-0 and the second goal of the evening came in the 28th minute when Modric played Jose Maria Callejon through on goal over the top of the Ajax defence, and the Spanish attacker fired in.
© AP Photos
Four minutes after the half-time interval Kaka found the target for Madrid, as he received a ball from Ronaldo and curled a left-footed shot from 20 yards into the top corner.
Callejon wrapped up the points for Madrid in the 88th minute when he headed in Alvaro Morata's cross from close range.