The 49ers beat the Buccaneers 27-14 with two red zone stops in the fourth quarter.
San Francisco won its second consecutive game to move to 7-3, while Tampa Bay fell to 4-6.
The Buccaneers had their chances for a comeback.
They reached the San Francisco 12, where they faced a second-and-four with 6:52 left. Baker Mayfield threw three consecutive incompletions as Tampa Bay turned the ball over on downs.
The Bucs, though, forced a three-and-out and a Mitch Wishnowsky punt, which Deven Thompkins returned 51 yards to the San Francisco 13 before Dee Winters pushed him out of bounds. The Bucs didn’t score.
On second-and-six from the San Francisco 9, tight end Cade Otton dropped a touchdown and 49ers rookie safety Jayir Brown picked Mayfield on the next play as Nick Bosa got a hit on Mayfield as he threw.
It was the first red zone interception by Mayfield in 240 pass attempts, dating to four years ago.
Brown was playing only because of a knee injury to Talanoa Hufanga, who was carted off in the second half. Brown gave up a 41-yard pass to Rakim Jarrett early but rebounded with the end zone pick of Mayfield.
The 49ers had 420 yards and got a perfect passer rating from Brock Purdy. It was the first time a 49ers’ quarterback has had a 158.3 passer rating in a full game since Steve Young and Joe Montana each accomplished it in 1989.
Purdy completed 21 of 25 passes for 333 yards and three touchdowns. His touchdowns went for 4 yards to Christian McCaffrey, 76 yards to Brandon Aiyuk and 3 yards to George Kittle. Aiyuk had five receptions for 156 yards, while Kittle caught eight for 89.
McCaffrey rushed for 78 yards on 21 carries and caught five passes for 25 yards.
Mayfield was 29-of-45 for 246 yards with a touchdown and an interception.