Match ends, Spain 2, Morocco 2.
Iago Aspas scored a stoppage-time equaliser - with the aid of VAR - as Spain scraped an unconvincing draw with Morocco to top Group B and secure a World Cup last-16 tie against hosts Russia.
Youssef En-Nesyri - who plays in Spain for Malaga - looked to have won it for Herve Renard's side when he powered in a superb header from fellow substitute Faycal Fajr's corner.
But Aspas flicked in Dani Carvajal's low cross to make it 2-2, with referee Ravshan Irmatov initially disallowing the goal before overturning the decision.
Spain won the group on goals scored as Portugal were held to a 1-1 draw by Iran - but had a tough night as they extended their unbeaten run to 23 games.
A dreadful mix-up between Andres Iniesta and Sergio Ramos had allowed Khalid Boutaib to stride through and give Morocco a surprise 14th-minute lead.
Iniesta made amends five minutes later by helping create a sublime equaliser, exchanging passes with Diego Costa and getting to the byeline before cutting back for Isco to steer high into the net.
But Spain looked wobbly in defence when pressed by a committed, aggressive Morocco side, with Boutaib denied by the legs of David de Gea after Hakim Ziyech's quick throw sent him clear.
Nordin Amrabat was desperately unlucky not to score in the second half as his searing shot came back off the angle of post and bar with De Gea motionless.
Isco was denied a second goal when his header was diverted wide by Romain Saiss - playing instead of dropped captain Medhi Benatia - before the late drama.
Spain wobble at the back
Spain have been hit and miss at this World Cup - perhaps unsurprisingly, given the turbulence surrounding the pre-tournament sacking of coach Julen Lopetegui.
They were excellent in their opening game against Portugal - but had to settle for a 3-3 draw - and poor in their second match against Iran - but won 1-0.
In Kaliningrad, they dominated possession - having more than 75% of the ball - and had 18 shots to Morocco's six. However, they produced a performance that must still have concerned new coach Fernando Hierro.
The game's first two goals were the clearest demonstration of Spain's strange display. Iniesta's loose return pass to Ramos was down to a lapse in concentration, allowing Morocco to take the lead, but his setting up of Isco's equaliser was beautifully done.
Spain were defensively off-key whenever under pressure, with Gerard Pique lucky to escape punishment early on for a two-footed lunge towards Boutaib - saved by the fact he did make contact with the ball - before he avoided sanction for a clear second-half handball on the edge of his own penalty area.
In Pique's defence, he nearly made amends with a header that veered just wide, from an Isco corner, but they were grateful to Aspas for securing them first place in the group - and ensuring they avoided the dangerous Uruguay in the next round.
Morocco make their point
There is a strong case for arguing that Morocco are the unluckiest team to be eliminated at the group stage - with poor finishing costing them a point against Portugal, and possibly all three against Iran.
As it was, they lost both of those games 1-0, meaning they were already out before they kicked off against Spain.
There has clearly been a lot of frustration building up in the Morocco camp in recent days - with captain Benatia criticising assistant coach Mustapha Hadji, the former Coventry midfielder, after Wednesday's defeat by Portugal.
That may have contributed to Benatia being left out of the team to face Spain - but those who did play went into the match with a point to prove.
At times, they were too aggressive - as a tally of six yellow cards showed, even if one or two of them were harsh.
However, their commitment made for an enthralling game in which they defended with great discipline and looked dangerous on the counter-attack.
Renard had complained before the game about refereeing decisions going against his team in their opening two games, and his players thought they had been on the wrong end of a decision when Aspas' goal was allowed to stand.
Frustrations threatened to boil over in a chaotic end to the game, with a cluster of players being involved in a confrontation - although television evidence suggested that referee Irmatov did get it right by allowing the goal after consulting with the video assistant refereeing team.
Man of the match - Nordin Amrabat (Morocco)
'Now we are facing the moment of truth' - what they said
Morocco coach Herve Renard: "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.
"We've lacked a bit of experience and there were games we should have had better results in. But we've shown that we can take on two of the best teams in the world, Portugal and Spain, and represent Morocco well."
Spain midfielder Isco: "Now we are facing the moment of truth but I have complete faith in this team.
"Morocco was a really tough match. Maybe we were lacking greater control of the game and normally that is what we do a lot better."
On facing Russia in the last 16: "It's going to be a tough game. They have the whole country behind them and play excellent football. We played a friendly against them ahead of the World Cup so we know about them."
29th time lucky for Morocco - the key stats
- Boutaib's goal for Morocco came from their 29th shot at this year's World Cup, and was their first goal at the finals since 1998, when Salaheddine Bassir scored in a 3-0 win over Scotland.
- Ramos made his 16th appearance for Spain at the World Cup, overtaking Xavi as their most capped outfield player in the competition.
- Spain have not lost a fixture - competitive or friendly - since defeat by Italy at Euro 2016.
- Morocco have won just one of their past 10 World Cup matches (two draws, seven defeats).
- Spain have failed to win their final group game at a World Cup for the first time since 1982, having won the previous eight such games.
- Isco has been directly involved in 12 goals in his past 15 international matches for Spain (10 goals, two assists).
- Aspas has been directly involved in 10 goals in his 10 appearances as a substitute for Spain (six goals, four assists).
- Spain have finished the group stages unbeaten for the first time since 2006, when they won all three matches.
- 1De Gea
- 10Thiago AlcántaraSubstituted forAsensioat 74'minutes
- 21SilvaSubstituted forRodrigoat 84'minutes
- 19Diego CostaSubstituted forIago Aspasat 74'minutes
- 17Iago Aspas
- 12MohamediBooked at 88mins
- 4da CostaBooked at 31mins
- 2HakimiBooked at 90mins
- 8El AhmadiBooked at 21mins
- 16N AmrabatBooked at 29mins
- 14BoussoufaBooked at 31mins
- 10BelhandaSubstituted forFajrat 63'minutes
- 7ZiyechSubstituted forBouhaddouzat 85'minutes
- 13BoutaïbSubstituted forEn-Nesyriat 72'minutes
- 9El Kaabi
- 21S Amrabat
- Ravshan Irmatov
- Shots on Target
Second Half ends, Spain 2, Morocco 2.
Marco Asensio (Spain) wins a free kick on the right wing.
Foul by Faycal Fajr (Morocco).
Delay over. They are ready to continue.
Achraf Hakimi (Morocco) is shown the yellow card.
Video Review: Goal. Referee decision on field cancelled.
Delay in match (Spain). Video Review.
Goal! Spain 2, Morocco 2. Iago Aspas (Spain) right footed shot from very close range to the bottom left corner. Assisted by Daniel Carvajal with a cross following a corner.
Corner, Spain. Conceded by Achraf Hakimi.
Munir Mohamedi (Morocco) is shown the yellow card.
Foul by Iago Aspas (Spain).
Romain Saïss (Morocco) wins a free kick in the defensive half.
Attempt missed. Marco Asensio (Spain) header from the centre of the box is close, but misses to the left. Assisted by Iago Aspas.
Attempt missed. Rodrigo Moreno (Spain) with an attempt from the centre of the box misses to the right. Assisted by Iago Aspas following a set piece situation.
Attempt missed. Iago Aspas (Spain) header from the centre of the box misses to the left. Assisted by Isco with a cross following a set piece situation.
Substitution, Morocco. Aziz Bouhaddouz replaces Hakim Ziyech.
Substitution, Spain. Rodrigo Moreno replaces David Silva.
Daniel Carvajal (Spain) wins a free kick on the right wing.
Foul by Hakim Ziyech (Morocco).