Spain's players celebrate at the end of the Russia 2018 World Cup Group B football match between Spain and Morocco. Photograph:( AFP )
Spain drew 2-2 with Morocco to top Group B thanks to a late Iago Aspas equaliser that was referred to the video assistant referee.
Fernando Hierro's Spain, the 2010 world champions, will play Russia in the next round in Moscow on Sunday.
On the other hand, European champions Portugal face Uruguay in Sochi the previous day.
Spain survived a real scare from a spirited Morocco side who had been leading 2-1 when the 90th minute began.
Aspas' clever flick from a wide free kick was initially adjudged by the assistant referee to have been offside.
But after intervention from VAR it was given as a goal, much to the consternation of the Moroccan players and substitutes, some of whom stormed the pitch in protest.
Morocco coach Herve Renard said before the game his team, the first to be eliminated this tournament, had been victim to "total injustice" in their opening 1-0 losses.
The North Africans, who had yet to score a point or even a goal before Monday, started brightly, compact without the ball and breaking at speed.
Morocco took the lead on 14 minutes when Boutaib took advantage of a horrible mix-up between Sergio Ramos and Andres Iniesta to race through and slide the ball calmly through David De Gea's legs.
Spain were level five minutes later when some crisp passing sent Iniesta free inside Morocco's box. He cut back with the outside of his right boot to Isco, who fired into the roof of Monir El-Kajoui's net from six yards.
The Real Madrid playmaker was at the heart of every Spain attack, caressing clever passes to teammates and weaving past wrong-footed defenders.
Boutaib missed a glorious chance to restore the advantage when he found Spain's centre backs sleeping off a quick throw only to fluff the one-on-one with De Gea.
But La Roja should have gone in ahead at half-time, with Iniesta's square pass missing Diego Costa's outstretched right boot by millimetres from point blank.
Morocco sat back in the second period and invited Spain to try to break them down.
When they regained possession they broke with pace and purpose, and nearly took the lead after 55 minutes when Noureddine Amrabat's right-foot scorcher from distance cannoned off the crossbar.
Isco's header on the hour mark forced a goal-line clearance from Ghanem Saiss, chosen by Renard to start over captain Mehdi Benatia.
Morocco were aggrieved not to be awarded a penalty 10 minutes from time when the ball struck Pique's fist in the area.
They weren't complaining minutes later, however, when substitute Youssef En-Nesyri headed home the corner that followed to the rapture of the Moroccan supporters.
But Aspas' late equaliser took some of the gloss of what had been a spirited and well-drilled performance.