The result extended North End’s unbeaten league run to 15 games, but second-placed Preston are now just three points clear of MK Dons in third with four games to play.
Jermaine Beckford gave the hosts the lead after 36 minutes when he was slipped in on the right edge of the area and lashed the ball past goalkeeper Glenn Morris with his right foot from 16 yards.
Callum Robinson then doubled the advantage on the stroke of half-time when he fired in a low shot from 20 yards into the bottom corner of the net.
Jermaine McGlashan stunned Deepdale by pulling one back with Gillingham’s first real chance when he broke clear and poked the ball under Sam Johnstone after 58 minutes.
Preston, unbeaten at home in the league since November, almost hit back instantly but Joe Garner’s shot was blocked on the line by Cody McDonald.
And Legge made the hosts pay by nodding Max Ehmer’s cross over Johnstone and into the far corner in added time.