Media playback is not supported on this device
Luka Pibernik punched the air as he crossed the finish line - but the route looped back for another lap in Messina.
He only appeared to realise his mistake after the peloton swept past.
Welsh Team Sky rider Geraint Thomas came home safely in the main bunch to stay second overall - six seconds behind race leader Bob Jungels.
Thomas' fellow Briton Adam Yates remains third - 10 seconds behind Jungels - on the same time as defending champion Vincenzo Nibali and 2014 winner Nairo Quintana.
Jakub Mareczko was second behind Gaviria - who also won Sunday's stage three - with Ireland's Sam Bennett third at the end of Wednesday's 159km route from Pessara.
Pibernik eventually finished 148th, 20 seconds slower than Gaviria.
Thursday's sixth stage is a 217km ride from Reggio Calabria to Terme Luigiane that features a category-three climb and a category-four climb.
1.  Fernando Gaviria (Col/Quick-Step) 3hrs 40mins 11secs
2.  Jakub Mareczko (Ita/Wilier Triestina) Same time
3.  Sam Bennett (Ire/Bora)
4.  Andre Greipel (Ger/Lotto)
5.  Phil Bauhaus (Ger/Sunweb)
6.  Kristian Sbaragli (Ita/Dimension Data)
7.  Ryan Gibbons (SA/ Dimension Data)
8.  Roberto Ferrari (Ita/UAE Team Emirates)
9.  Jasper Stuyven (Bel/Trek)
10. Enrico Battaglin (Ita/LottoNL)
1. Bob Jungels (Lux/Quick-Step) 23hrs 22mins 07secs
2. Geraint Thomas (GB/Team Sky) +6secs
3. Adam Yates (GB/Orica) +10secs
4.  Domenico Pozzovivo (Ita/AG2R) Same time
5. Vincenzo Nibali (Ita/Bahrain)
6. Tom Dumoulin (Ned/Sunweb)
7. Nairo Quintana (Col/Movistar)
8. Bauke Mollema (Ned/Trek)
9. Tejay van Garderen (US/BMC)
10. Andrey Amador (Crc/ Movistar)
Fernando Gaviria won his second stage at the Giro d'Italia in a sprint finish, after another rider celebrated 'winning' stage five with 6km to go.