Morocco had taken the lead in the 14th minute through Khalid Boutaib, before Spanish midfielder Isco had drawn things level with a fine finish from inside the box.
Spain fell behind for the second time in the match from a corner taken by Faycal Fajr which was whipped in from the right-hand side.
En-Nesyri, who plays his club football for Malaga in Spain, arrived to meet the ball and rose above Spain captain Sergio Ramos.
His header flew in to the net to the left of David De Gea, who could only stand and watch his side fall behind with only 10 minutes left in the match, leaving Spain hurredly trying to get another equaliser to guarantee their progression in to the last 16 of the tournament.