Morocco were denied a shock World Cup win against Spain in their Group B finale on Monday when VAR overturned an offside call on a late Iago Aspas goal as the match finished 2-2.
The result, combined with Portugal's 1-1 draw against Iran, sees Spain through to the round of 16 as group winners because of total goals scored and will now face Russia in the knockout round.
A tense opening 10 minutes saw Spain have the better of possession, but Morocco take the lead when Khalid Boutaib picked up the ball at midfield from a Sergio Ramos giveaway, charged in on goal and beat David De Gea with a composed finish to give his team the lead and their first goal at the World Cup since 1998.
Spain wasted no time equalising when Andres Iniesta set Isco up at the top of the six-yard box with a clever pass and the Real Madrid man took one touch and then smashed a shot into the roof of the net.
Morocco almost retook the lead minutes later again through Boutaib, who was in on goal from a long throw in, but this time De Gea got down to keep out the striker's close-range effort.
The teams came out of the dressing room for the second half level at 1-1 and it was Spain that were again on the front foot only to see Morocco fashion the best early chance when Nordin Amrabat's swerving shot from outside the area smashed off the crossbar with De Gea easily beaten.
Spain then went close twice just after the hour mark with Isco's goal-bound header cleared off the line by Morocco's Romain Saïss before Gerard Pique nodded just wide of the far post from a set piece.
With the match seemingly headed for a draw, Youssef En-Nesyri rose highest in the 81st minute to power a header past a helpless De Gea into the back of net and put his team on the brink of a historic win.
But Aspas' neat flick from a Dani Carvajal cross -- initially ruled out for offside -- was awarded after video review showed the Celta Vigo striker to be onside when the ball was played into the area.
Spain are the first team to win its group with five or fewer points since the United States and Paraguay in 2010 when La Roja finished as eventual champions.