Madrid had to play without Kylian Mbappe and Jude Bellingham after they suffered minor injuries. The team was already dealing with a defensive injury crisis, which meant young players Jacobo Ramon and Raul Asencio had to step up to be at the heart of their back-line.
"Gonzalo has been in a very good run with the reserves and he brought a lot," Madrid coach Carlo Ancelotti told reporters.
"We have to be pleased with what the young players did... they are well prepared, they lack experience obviously, but they are doing very well."
Madrid started the quarter-final well and were soon ahead, with Modric slotting home in the 18th minute after good work by in-form winger Rodrygo.
Teenage striker Endrick doubled Los Blancos' lead with a poacher's finish after the ball broke loose to him in the box.
It seemed to be plain sailing for Ancelotti's side until Jacobo conceded a penalty for handling Cruz's shot.
Advertisement
The Leganes playmaker dispatched the spot kick low to Andriy Lunin's left, with the Ukrainian goalkeeper inches away from reaching it.
Ancelotti sent on Vinicius Junior for Rodrygo for the second half, and the winger missed two good chances straight away.
Leganes goalkeeper Juan Soriano saved well to deny the Brazilian, who also headed over from close range.
Madrid paid the price for their profligacy when Cruz netted his second, with the aid of a deflection off Ferland Mendy.
Advertisement
With stoppage time almost over, Diaz produced a fine dribble to break free on the right, before crossing to the near post to create his side's late winner.
Gonzalo was on hand to head home with one of the final touches of the game and book Madrid's ticket to the semi-final.
League leaders Madrid face Atletico, second, on Saturday in a derby clash before visiting Man City in the Champions League on Tuesday.
"(Gonzalo's) goal came just in time, in the last minute," said Ancelotti.
"Obviously it takes you a bit longer to recover from playing extra-time.
"The team is in good shape, we left some players out for them to rest a bit, to be ready for Saturday and well prepared."
Listen to the latest songs, only on JioSaavn.com
Atletico thrashed Getafe 5-0 on Tuesday to progress to the final four, while record 31-time winners Barcelona visit Valencia and Real Sociedad host Osasuna in the other quarter-finals on Thursday.
(This story has not been edited by staff and is auto-generated from a syndicated feed.)