Missed the match? Catch Up via beIN SPORTS CONNECT
Bafana Bafana, who shocked host Egypt in the previous round, had equalised with 19 minutes remaining in Cairo when Bongani Zungu headed home and the match was seemingly headed for extra-time.
But Troost-Ekong bundled home in the 89th-minute minute after Williams made a hash of a corner to dash South Africa's hopes of progressing and left Nigeria still chasing their dream of a fourth AFCON title.
It was a just result for a Nigeria team after they had largely dominated and led in the 27th minute through Samuel Chukwueze, who was part of a lively Nigeria front four that opened South Africa up several times.
The result extends South Africa's record of never having beaten Nigeria at the Cup of Nations, while Gernot Rohr's men moved into the last four – where Ivory Coast of Algeria await - with a disciplined, determined performance.