Winning Group B means Spain go on to face tournament hosts Russian Federation who looked good in their opening two matches but were comfortably beaten 3-0 by Uruguay on Monday.
But he proved his value to Spain in the second half - first denying Boutaib a second goal with a save at the near post and then punching away a risky ball in the 50th minute as Mbark Boussoufa tried to reach a cross.
Second-half substitutes combined when Faycal Fajr's corner from the right was headed home by Youssef En-Nesyri to send the Moroccan fans into delirium.
Spain will play Russian Federation in the last 16 of the World Cup, but needed a lot of luck and a major moment of video assistant referee drama to seal top spot in Group B. Late goals in both games meant Portugal and Spain both drew their final group games, with La Roja's goals scored tally the only thing deciding which Iberian side finished first.
Spain were poor in defence, but in attack they still played as fluently as ever, and Iniesta and Isco highlighted just how crucial they are to their World Cup hopes.
A heart-pumping game that could have been a disaster for Spain.
The fightback could prove crucial in Spain's quest to regain the World Cup.
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.
Brian Harman takes one-shot lead in Travellers Championship
Although Spieth emerged victorious in the 2017 Travelers championship , he has had some trouble at No. 13 in the past. Sometimes it can get disguised by rounds, but it's not far off.
"We would have loved to get a win over Spain, this is why we came here tonight".
The first half was otherwise notable for a number of crunching challenges - Morocco receiving four yellow cards and Spain defender Gerard Pique was perhaps fortunate not to be set off for a two-footed lunge. The result saw them top their group after Portugal failed to beat Iran as they drew 1-1.
They utterly dominated Iran in their second game but had to settle for a narrow 1-0 win after being frustrated for long periods against Carlos Queiroz's side.
Morocco sat back in the second period and invited Spain to try to break them down.
De Gea was criticised after his blunder gave Ronaldo one of his three goals in in Spain's draw with Portugal.
Spain will now face hosts Russian Federation in Moscow on Sunday for a place in the last eight.
De Gea finally made his first stop of the tournament to deny Morocco the chance to go back in front following Spain's well-worked equaliser.
Noureddine Amrabat, who suffered a head injury in Morocco's first World Cup match, showed the intensity that coach Herve Renard wanted from his team as it played its last match of a disappointing World Cup.