Portugal defeated Mexico 2-1 on Wednesday to take maximum points from Group D and set up a knockout round clash with the second placed team in Argentina's group. Iran drew 1-1 with Angola in the other Group D game, leaving Mexico in second place with the prospect of meeting either Argentina or the Netherlands in the next round.
The Mexicans did their best to self-destruct - giving away a first-half penalty, missing a second-half spot kick and having Luis Perez sent off -but they qualify with four points.
Maniche put Portugal ahead and Simao made it two from the spot after Marquez had handled. Fonseca pulled one back for Mexico and Bravo missed a penalty after a hand-ball from Miguel.
Angola's hopes of World Cup glory were dashed when Iran rallied to draw 1-1, depriving them of second place. The World Cup debutants had needed to win by two goals to qualify for the knockout stage.
Second half substitute Amado Flavio headed Angola's first World Cup goal in the 60th minute but Sohrab Bakhtiarizadeh headed a 75th minute equaliser for Iran.
Portugal finished top on 9 points, followed by Mexico (4), Angola (2) and Iran (1).
The pairings for the next round will be known after the Group C encounter between top two Argentina and the Netherlands in Frankfurt later Tuesday.
Portugal will face the second placed team in Group C in Nuremberg on Sunday, while Argentina meet the group winners in Leipzig a day before.