Nahki Wells scored his first goal for Bristol City as they held off a spirited comeback from Derby County to claim a thrilling 3-2 Sky Bet Championship victory at Ashton Gate.
The hosts took a 38th-minute lead when Niclas Eliasson's deep cross from the right was volleyed back across goal by Jay Dasilva for Wells to mark his first start for the Robins with a powerful header.
It was 2-0 just before the break as Derby were again found wanting in the air. Famara Diedhiou's header from a right-wing corner was blocked, but centre-back Filip Benkovic pounced to nod home.
The Rams did not learn their lesson and Ashley Williams headed down another Eliasson cross for Diedhiou to volley home a third after 58 minutes.
It looked to be all over, but three minutes later Martyn Waghorn dived to head home a Max Lowe cross and spark a spell of intense Derby pressure.
Chris Martin tapped home a low cross from Tom Lawrence in the 82nd minute to set up a frantic finish in which Lawrence had a deflected shot saved by City goalkeeper Dan Bentley.
Diedhiou and substitute Andreas Weimann missed great stoppage-time chances to make it 4-2 at the death, but the final whistle was greeted with cheers of relief from home supporters.
The first half had been a closely-fought affair until Wells' opener. Waghorn, who picked up an early yellow card for a late challenge, fired wide from distance for Derby after three minutes.
Wayne Rooney was applauded by a section of City fans and baited by others as he attempted to pull the strings for the visitors from a deep midfield role.
His efforts gave Derby the edge and Duane Holmes forced a save from Bentley at his near post with a 17th-minute drive.
Benkovic headed over from an Eliasson corner and debutant midfielder Markus Henriksen fired wide from 25 yards as City applied pressure for the first time.
After Wells had broken the deadlock, Lee Johnson's team produced their best football and Diedhiou brought a smart save from Ben Hamer with a deflected shot.
The second goal came with City well on top, but the final action of the half saw Rooney shoot wide from the edge of the box.
If the home side thought they were home and dry when Diedhiou made it 3-0, they were in for a rude awakening as Waghorn's riposte spurred his side into their best spell.
There was a loud appeal for a penalty when Williams appeared to block a cross with an arm.
At the other end, Wells shot high over the crossbar from an excellent chance and it was end-to-end action as both teams committed to attack.
Having lost four of their previous six home league games, it was a huge result for City in their challenge for the play-offs.