Rahimi's brace took him to eight goals at the Olympics, cementing his status as the tournament's top scorer, while Abde Ezzalzouli, Bilal El Khannouss and Akram Nakach also scored in a comprehensive win at the Stade de la Beaujoire in Nantes.
Hakimi's late strike put the icing on the cake as Morocco claimed a first Olympic football medal, and a first for North Africa.
Morocco, who beat Argentina in their opening group game and were eventually beaten by Spain in the semi-finals, had already defeated Egypt in the final of last year's Under-23 Africa Cup of Nations.
That success was what allowed them to qualify for the Olympics, and they secured a medal in rampant fashion with Ezzalzouli, of Real Betis in Spain, putting Morocco ahead from a superb strike just inside the box midway through the first half.
Rahimi made it 2-0 shortly after when he headed in a cross by Ezzalzouli, before the Atlas Lions ran away with the game in the second half.
El Khannouss curled a low shot into the bottom-right corner from just outside the box for the third goal, and Rahimi got his second to make it 4-0 when he controlled a pass by Ilias Akhomach before firing in.
Striker Rahimi, who has at least four more goals than any other player in the tournament, then turned provider for defender Akram Nakach to make it five.
However, Hakimi saved the best for last by finding the net with a missile of a free-kick from 30 metres three minutes from the end. That was Morocco's 17th goal in six matches at the Games.
Hosts France play Spain in the gold medal match in Paris on Friday.