Almagro, ranked 76th, broke Djokovic in the opening game but the world number two roared back to win six consecutive games, finishing the last with a tidy drop shot.

Spaniard Almagro, who has never gone beyond the quarter-finals in a grand slam, grew in confidence in the second set, however, with the backing of the home support and saved two break points before forcing a decider.

An upset looked on the cards when Almagro broke Djokovic at the first attempt in the third set and marched into a 3-0 lead but the Serb drew on his experience to battle back, breaking the 31-year-old twice before serving out for the match.

The Serbian, who recently split from his long-term coach Marian Vajda, is trying to regain his best form again ahead of the French Open. Four-times winner Nadal twice bounced back to win the first set in a thrilling tiebreak.

Fognini played aggressively, however, and forced Nadal on to the defensive as he took the match into a deciding set.

After failing to take advantage of one match point, Nadal emerged victorious thanks to two powerful forehands and the 30-year-old world number five next faces Australian Nick Kyrgios.