The 37-year-old Spaniard needed three hours and six minutes on the court to win 6-1 6-7 (5-7) 6-3.
The five-time winner Nadal is in what he believes to be his final season of competition, playing for the last time on the Madrid clay.
To advance to the quarterfinals, Nadal will face Czech Republic’s Jiri Lehecka, the 30th seed, on Tuesday.
However, after falling to fifth seed Casper Ruud in straight sets, Cameron Norrie of Great Britain is eliminated.
After winning in Barcelona the previous week, the Norwegian won 6-2 6-4 and will play Felix Auger-Aliassime of Canada in the next round.
Norrie led by break early in the second set, having lost the opening set after being broken in his opening service game of the match.
Ruud, though, answered quickly to level it 3-3 and then broke to love to seal the win.