It was the reverse of last year’s final, when Federer won his fourth title in Hamburg and snapped Nadal’s 81-match winning streak on clay.
Nadal rallied from big deficits in the first two sets, although he lost the tiebreaker in the second. He led 4-1 in the third and held on to raise his record against the top-ranked player to 8-1 on clay and 10-6 overall.
“All the week has been very special for me,” Nadal said.
The second-ranked Spaniard has 26 career titles, 21 of them on clay, including the last three French Opens. Nadal also won in Monte Carlo — beating Federer in the final — and Barcelona this year.
“It was a strange match,” Nadal said. “Roger made some mistakes in the first set that helped me. ... It was important to win because it was the last big clay-court tournament I never won.”
Federer lost his seventh match of the year and has only one title so far, at a relatively minor clay-court tournament in Estoril, Portugal.
The Hamburg Masters is a major warm-up tournament for the French Open, the only Grand Slam that Federer has not won.
“I could have served a little better; it wasn’t my best performance, maybe. I have to go for big serves — he is a good return player,” Federer said. “It was a fun match.”
Federer went into Sunday’s final with a 41-match winning streak in Germany and a 9-0 career record in finals on German soil. His last loss in Germany was in 2003.
Federer has been No. 1 since February 2004, but Nadal is the top player on the slower clay surface. Since April 2005, he has lost only twice in 110 matches on clay — to Federer last year in the Hamburg final and last week in Rome to Juan Carlos Ferrero, when Nadal was slowed by a painful blister on his foot.
Federer led 5-2 in the first set and wasted two set points before Nadal completed a comeback by winning seven straight games. That gave him the first set and a 1-0 lead in the second.
Federer then won the next four games and went on to lead 5-2, but could not close out the set before the tiebreaker.
Nadal had a three-hour match Saturday in beating Novak Djokovic in three sets to protect his No. 2 ranking, but he appeared fresher in the third set Sunday.
Serving for the match, Nadal won the first three points and then hit a backhand crosscourt winner. He fell to his knees and looked to the sky.
“I am happy that I won and that I beat the No. 1 in the world and the best player of the year (Djokovic), and that should give me some more confidence for the French Open,” Nadal said.
Nadal became only the third player to own all three clay-court Masters Series titles, in Rome, Monte Carlo and Hamburg.
“He had a great week and a great clay-court season,” said Federer, who finished with 41 unforced errors to Nadal’s 28.
ALSO ON THIS STORY Discuss: Sound off on tennis message boards
Tsonga beats Mahut to advance at Hamburg Masters
Collins: Federer down but not out