Anthony Lozano gave Girona an early lead at the Santiago Bernabeu on Thursday, but Madrid battled back thanks to Lucas Vazquez's equaliser and a Ramos penalty.
Another spot-kick saw Girona equalise, Alex Granell stepping up to convert after Marcos Llorente needlessly handled the ball in the box, but Ramos and Karim Benzema struck late.
Madrid's captain rose highest in the box to crash home a header from Marcelo's cross and Girona's hopes were dashed when Benzema slotted in a Vinicius Junior cross.
Madrid forced a trio of early corners, but Girona took the lead with their first attack in the seventh minute, Raul Garcia given too much space on the left to deliver a cross Lozano met on the volley.
The hosts soon levelled, though, Benzema sending Alvaro Odriozola clear in the right channel to pull back a low pass that Vazquez placed home.
Madrid led in the 42nd minute, Ramos beating Gorka Iraizoz with a Panenka from the spot after Vinicius's feet were too quick for Lozano on the edge of the box.
Benzema clipped the post before the break but when Llorente thrust out his hand to deflect a cross Girona made the tie all square, Granell confidently smashing his penalty beyond Thibaut Courtois.
Vinicius was involved again as Madrid regained the lead in the 77th minute, getting into space on the left to tee up Marcelo for a cross Ramos was never going to miss.
Madrid were not finished, however, and substitute Isco threaded a pass through for Vinicius, who slipped a low cross into the box that Benzema gobbled up to give Santiago Solari's side a two-goal cushion.
What does it mean? Madrid showing signs of improvement
Santiago Solari's side crave elusive momentum and they needed Ramos to bail them out yet again, but a clinical close to the game put them in control. Eusebio Sacristan's Girona may have caused an even bigger shock had leading scorer Cristhian Stuani started the game, but having knocked Atletico Madrid out in the last round they will still feel they have a chance.
Vinicius growing into leader of Madrid's attack
Replacing Cristiano Ronaldo was always going to be a huge challenge for Madrid, but Brazilian winger Vinicius is continually enhancing his stature at the Santiago Bernabeu. He won the penalty that saw Madrid take the lead and was a constant threat off the wing with his pace and tricks, setting up Benzema for the last goal of the game.
Llorente's moment of madness could be costly
What Llorente was thinking when he stuck out an arm in his own penalty box is hard to imagine, with the young midfielder fortunate his error - committed just seven minutes after coming on for Casemiro - has not cost Madrid a first-leg lead. He has been one of the major successes of Solari's spell, but with Toni Kroos returning to fitness after over two weeks out he may be spending more time on the bench.