The Scotland international had been linked with a move away from Ibrox this summer but he has now committed himself to the club for the foreseeable future.
McGregor, 26, told the Gers' official website: "I'm delighted with the five-year deal, it's good to get it settled and hopefully now I can just get on with pre-season."
The end of the season brought speculation of a move to the Premier League, with both Tottenham and Newcastle reportedly planning a summer swoop.
But McGregor, who previously had loan spells at St Johnstone and Dunfermline, insists staying with Rangers was always his first choice.
He said: "I met the chairman (Sir David Murray) a couple of weeks ago and I think he realised I always wanted to stay at the club, especially after breaking into the team."
Walter Smith was pleased to clinch the long-term deal for his first-choice goalkeeper.
Smith said: "We're delighted to secure Allan on a long-term contract.
"He had a great season last year before his injury.
"He's come through the youth ranks at the club and is now an established first-team star and that's testament to his hard work and ability."