Bafana Bafana led in the 57th minute when midfielder Themba Zwane, so often the creative fulcrum of the side, slipped a pass through to tall striker Evidence Makgopa and he calmly slid the ball past goalkeeper Yassine Bounou, before Teboho Mokoena fired in a superb late free kick.
Morocco had a chance to level with the score at 1-0 when they were awarded a penalty, but Achraf Hakimi hit the crossbar.
South Africa will play Cape Verde in the quarter-finals in Yamoussoukro on Saturday.
South Africa, winners in 1996, have endured much hardship in continental competition over the last few decades and have not been past the quarter-finals since 2000, but put in a stoic defensive display to go with flashes of attacking quality to seal a famous win.
Morocco looked to suffer in the oppressive heat and were a far cry from the entertaining side that delighted at the World Cup in Qatar, missing on this occasion the attacking talents of injured playmaker Hakim Ziyech.
They could not break their opponents down, and even when gifted a clear penalty following a handball by defender Mothobi Mvala, Hakimi summed up their night by hitting the frame of the goal.
The first half was devoid of many clear-cut chances as South Africa took a cautious approach and played a containment game, keeping their structure and not throwing bodies into attack.
Mokoena forced a good save from Bounou with a shot from 30-yards, while Percy Tau headed wide from a corner.
But the best opportunity of the opening 45 minutes fell to Moroccan winger Amine Adli just before halftime. He delayed his shot from 10 yards and that allowed the covering defence to get across and close him down.
Once Makgopa had given South Africa the lead, they went even further into their shell, relying on the counter-attack.
Their second goal was a sublime free kick from dead-ball specialist Mokoena in the fifth minute of stoppage time as he smashed the ball into the back of the net after Sofyan Amrabat had been red carded for a professional foul.