The centre-half headed home a second-half free kick from Luka Modric to drag Carlo Ancelotti's men right back into the title raceReal Madrid's unlikely hero as his goal saw the gap at the top of La Liga cut to three points with a 1-0 win over Espanyol.
With Barcelona and Atletico Madrid drawing on Saturday the pressure was on Carlo Ancelotti's side to move within striking distance of the top two against a side they have not lost to since 2007.
The visitors struggled to deal with that pressure in the opening half but finally broke the deadlock in the 55th minute as Portugal defender Pepe rose unmarked to head home his third league goal of the season.
Mid-table Espanyol had executed Javier Aguirre's plans perfectly in the first half and restricted Madrid to shots from the edge of the area that Kiko Casilla was able to deal with.
Despite the goal Madrid were still far from their fluent best but they had enough to secure the victory and extend Aguirre's winless run against them to 10 games in the league.
Ancelotti made just one change from Madrid's last league outing, as Gareth Bale replaced Isco, the Wales international playing alongside Cristiano Ronaldo and Angel di Maria in support of Karim Benzema.
The hosts, who made six changes, started brightly but were unable to test Diego Lopez before Madrid got into their stride and nearly opened the scoring in the seventh minute.
Di Maria delivered a tempting cross into the penalty area where Benzema swivelled to volley towards the target, but the ball flew just wide of Casillas' goal.
Espanyol were not intimidated by their illustrious opponents and went close through Jhon Cordoba, but the striker fired wide after skipping past two Madrid challenges.
Ronaldo, who had been fairly quiet in the opening stages, twice went close to breaking the deadlock just after the half hour.
His first effort, a swerving shot in the 32nd minute, was punched clear by Casilla and the keeper saved a free kick from the Portugal international with his feet four minutes later.
After another 10 minutes of frustration for the visitors at the start of the second half, Pepe raised their spirits with a towering header from a Luka Modric cross to give Madrid the lead.
Pepe's central defensive partner Sergio Ramos nearly doubled the lead in the 67th minute, but his header from a Daniel Carvajal cross was straight at Casilla.
Casilla thwarted Ronaldo and Benzema in the closing stages as Real went in search of a second, but one proved enough to extend their winning run to five matches in all competitions.