Fiji moved into the last eight at a rugby union World Cup for the first time since 2007, despite losing to Portugal in a thrilling match in Toulouse on Sunday night.
The teams went into the pause level at 3-3 after Frank Lomani and Samuel Marques swapped penalties.
The sides exchanged tries immediately after the restart. Rafaelle Storti scored for Portugal and Levani Botia responded.
But at 10-10, Fiji hit the self-destruct button. Botia was sent to the sin bin for a dangerous tackle on Rodrigo Marta.
During his absence, Francisco Fernandes scored and Marques converted to make it 17-10.
Recovery
The Fijians ground their way back with a try from Mesake Doge and Lomani converted to square matters up at 17-17.
Eight minutes from time Lomani kicked a penalty for Fjii to lead 20-17. And a few minutes later, Portugal conceded another penalty and Lomani added three more.
But at 23-17, Fiji kicked away possession and Portugal made them pay. Storti ran free down the right and as Lomani tackled him, he offloaded to Marta who ran in for the try.
Marques converted the try to take them ahead 24-23. Portugal held on for their triumph.
Heading to quarter-finals
Fiji, who gained a defensive point for their efforts, finished on 11 points – the same tally as Australia. But the Fijians progress as runners-up in Group C because they beat Australia on 17 September.
Earlier, Argentina booked their place in the last eight with a 39-27 win over Japan.
The South Americans came second in Group D and will play the Group C winners Wales in Marseille next Saturday afternoon.
Fiji will take on England – the Group D winners – on Sunday afternoon in Marseille.