The center back headed home a second-half free kick from Luka Modric to drag Carlo Ancelotti's men right back into the title race.
With Barcelona and Atletico Madrid drawing Saturday the pressure was on Carlo Ancelotti's side to move within striking distance of the top two against a team it has 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.
Midtable 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 was still far from its fluent best, but it had enough to secure the victory and extend Aguirre's winless run against Los Blancos to 10 games in the league.
Ancelotti made just one change from Madrid's last league outing, as Gareth Bale replaced Isco, with 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 volleyed toward the target, but the ball flew just wide of Casilla's goal.
Espanyol was not intimidated by it illustrious opponent 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 advantage 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 the winning run to five matches in all competitions.