Substitute Mikel Merino tipped the balance for Luis de la Fuente's team as he slotted past Diogo Costa as the clock ticked past 90 minutes.
With their tournament slipping away, Portugal rallied in added time, and fellow sub Bernardo Silva headed agonisingly wide of the post in the closing seconds.
As Silva beat the ground in frustration, there was an unsavoury moment inside Spain's penalty box, as his former Manchester City teammate Rodri appeared to celebrate in his face.
Silva furiously chased after Rodri and needed to be held back by Spain No.1 Unai Simon before referee Antony Taylor eventually blew the final whistle.
Rodri was asked about the incident in his post-match interview and the La Roja captain admitted he went too far.
"I made a mistake because I celebrated when he missed. I apologised to him immediately, and it was accepted because of the trust we have, that's all."
Merino's goal means Spain are now through to the World Cup quarters for the first time since they lifted the trophy back in 2010 and De la Fuente's charges will take on Belgium on July 10.
