MIAMI GARDENS, Fla. (AP) — Jordan Phillips drew a costly penalty for taunting his former team, setting up a touchdown with nine minutes left that helped the Miami Dolphins rally past the Buffalo Bills 21-17 on Sunday.

Miami turned away two Bills drives down the stretch, and Charles Clay almost caught Josh Allen's desperation fourth-down pass with a diving attempt at the goal line in the final minute.

Allen threw for 231 yards and ran for 135 to set a franchise record for rushing yards by a quarterback for the second week in a row. Buffalo lost despite outgaining Miami 415-175.

The Dolphins (6-6) snapped a two-game losing streak and won for only the third time since Week 3, helping their slim playoff chances. The Bills (4-8) will play their customary role of spoilers in the final weeks, assured of finishing at .500 or worse for the 16th time in the past 19 years.

Phillips had said he wanted to settle old scores after being released by the Dolphins in Week 5, but his eagerness to get the last word backfired.

Miami was trying to rally from a three-point deficit when Phillips tackled Kenyan Drake for a 4-yard loss deep in Bills territory. Phillips then rose, pushed Drake's leg away and drew a 15-yard penalty for taunting.

One play later, the Bills stopped Miami for another loss, and Phillips applauded in the direction of the Dolphins' bench. Bills coaches then took him out of the game, and he watched from the sideline as Ryan Tannehill hit Kenny Stills with a 13-yard scoring pass for a 21-17 lead.

Allen then drove the Bills to the Miami 23 before he was sacked on consecutive plays, and Stephen Hauschka missed a 55-yard field goal attempt. The Bills drove 65 yards in the final 2 1/2 minutes but again came up short.

Buffalo's rookie quarterback threw touchdown passes of 15 and 25 yards to Zay Jones, and the duo also connected on a two-point conversion. But Allen was intercepted twice by Xavien Howard and twice missed open receivers for potential scores.

A muffed punt by the Bills' Isaiah McKenzie led to the Dolphins' second touchdown, which put them ahead 14-6.

INJURY REPORT

Bills C Russell Bodine left the game in the first quarter with a left leg injury and did not return.

Dolphins reserve CB Cornell Armstrong left the game with a knee injury.

UP NEXT

The Dolphins play host to AFC East leader New England on Sunday. The Patriots won the earlier meeting 38-7 in Week 4.

The Bills play at home Sunday against the New York Jets, who lost an earlier meeting 41-10 in Week 10.