MIAMI GARDENS, Fla. (AP) — Josh Allen threw a go-ahead touchdown pass to Dawson Knox midway through the fourth quarter, and the Buffalo Bills won their fourth straight AFC East title, rallying past the Miami Dolphins 21-14 on Sunday night.

Allen made things difficult for the Bills with three turnovers in Miami territory, but he came through at the end to help Buffalo earn the No. 2 seed in the conference. The Bills, who didn’t clinch a playoff berth until Tennessee beat Jacksonville earlier Sunday, will host seventh-seeded Pittsburgh in the wild-card round on Sunday.

Buffalo was 5-5 in mid-November and faced long odds just to make the playoffs, but went 6-1 down the stretch, including five straight wins to finish the season, to get in with plenty of momentum.

Miami, which made the postseason with its Week 16 win over Dallas, fell to the sixth seed and will play at AFC West champion Kansas City on Saturday night.

The Bills dominated time of possession and outgained Miami by nearly 200 yards, but Buffalo trailed 14-7 before Deonte Harty returned a punt 96 yards for a touchdown early in the fourth quarter.

Buffalo forced a three-and-out, and Allen directed an eight-play, 74-yard drive, capped by his 5-yard toss to Knox with 4:52 left.

Miami had one last chance, but Taylor Rapp intercepted Tua Tagovailoa on a pass intended for Chase Claypool with 1:13 left.

Allen finished 30 of 38 for 359 yards and two TDs. He was intercepted on back-to-back drives to open the game, and he squandered another scoring chance when he completed a pass to Ty Johnson short of the goal line at the end of the first half, allowing time to expire.

A promising Buffalo drive in the third quarter ended when Allen was strip-sacked by Christian Wilkins.

Tagovailoa finished 17 of 27 for 173 yards with two interceptions. He had a 3-yard touchdown throw to Tyreek Hill in the second quarter. Rookie running back De’Von Achane’s shifty 25-yard score in the second quarter put Miami ahead 7-0.