Los Blancos started the afternoon 10 points adrift of bitter rivals Barcelona in the table, but goals from Karim Benzema and Casemiro, coupled with Ronaldo's rebound from his own missed penalty, helped them cut the Catalans' lead.
Real started the match well, taking the lead in the ninth minute when Brazil international Marcelo made a pacey run along the flank and crossed for Ronaldo to head towards goal.
The Portugal international's header beat Malaga goalkeeper Roberto and came back off the crossbar, allowing his strike partner Benzema to steer home the rebound from close range.
Malaga were fearless in their approach and restored the parity less than 10 minutes later through Diego Rolan, who found space in the box after collecting Keko's cross, and blazed a low strike beyond Kiko Casilla.
In an open match in which both sides made crucial defensive errors, there were more goals to come and Real were back in front with 21 minutes on the clock as Casemiro headed Toni Kroos's corner beyond Roberto to send his side into the break with a slender lead.
Los Blancos created the best chances early in the second half, with Ronaldo and Kroos both coming close, but they were pegged back against the run of play on 58 minutes when Chory Castro let fly from 25 yards and an awkward bounce helped the ball find its way beyond Casilla and into the net.
A nervy atmosphere set in around the stadium as the home support knew that dropping points would be a blow to their title hopes, but Real were given the chance to edge their noses back in front from the penalty spot in the 75th minute when Luis Hernandez brought down Luca Modric in the box.
Ronaldo stepped up to take the kick, and although his penalty was saved by Roberto, the Portuguese reacted quickly to put the rebound into the back of the net.
The former Manchester United striker had a second goal ruled out for offside in the closing stages, but in the end, Real did not need it to secure maximum points.
The win puts Zinedine Zidane's side within three points of Valencia in second and seven away from table-topping Barca, with the top two due to play each other on Sunday.
Real Madrid (4-4-2): Casilla; Carvajal, Vallejo, Varane, Marcelo; Isco (Modric 62), Kroos (Hernandez 81), Lucas Vazquez, Casemiro; Ronaldo, Benzema (Mayoral 89)
Malaga (4-2-3-1): Roberto; Rosales, Luis Hernandez, Diego Gonzalez, Juankar (Baysse 36); Recio, Adrian; Keko (Juanpi 66), Gontan, Chory, D. Rolan; Penaranda (Baston 61)