Substitute Iago Aspas had cleverly sent a back-heeled flick into the net. But the goal, from a Dani Carvajal cross, was initially disallowed for offside. The video assistant referee, however, overruled the on-field decision, sparking a touchline melee involving players from both sides at the Kaliningrad Stadium.
The already-eliminated north Africans got their first goal of the World Cup after 14 minutes, when a mix-up by Andres Iniesta and Sergio Ramos gifted Khalid Boutaib a chance. He pounced on the loose ball to score.
Morocco’s surprise lead lasted only five minutes, though, as Iniesta made amends by setting up Isco at the other end.
It was 1-1 at half-time and for most of the second half before substitute striker Youssef En Nesyri, headed Morocco in front in the 81st minute.
Noureddine Amrabat had earlier rattled the junction of post and bar with a powerful shot in the 55th minute that Spain keeper David De Gea could only watch as it bounced to safety. De Gea, pictured, had been criticised after his blunder gave Ronaldo one of his three goals in Spain’s 3-3 draw with Portugal. But he proved his worth in the second half, first denying Boutaib a second goal with a save at the near post and then punching away a dangerous ball in the 50th minute with Mbark Boussoufa poised to put it in.
With Portugal also drawing with Iran, Spain won the group on goals scored and will now play hosts Russia on Sunday in Moscow.
However, despite extending their 23-game unbeaten run, Spain were far from convincing, again showing defensive frailty after conceding that hat-trick to Cristiano Ronaldo in the draw with Portugal in their group opener.
They only managed a 1-0 win over Iran in their second game and, against a Morocco side who were only playing for pride, they struggled as the Atlas Lions defended stoutly and regularly threatened with speedy counter-attacks.
Afterwards, Morocco boss Herve Renard said: “This World Cup has been an exceptional experience. I came here to learn and we have learned a great deal over the three matches. We would have loved to have gone into the next round but we should be proud of what we have done and what we have achieved.
“We suffered, as every team that plays against Spain suffers, because their line-up is a mix of Real Madrid and Barcelona players – all exceptional.
“But I think our players, the whole team, should be commended for this game and the entire World Cup.”