The defending three-time world champion dominated the session and delivered a best lap in one minute and 18.704 seconds, two-tenths of a second clear of championship leader Rosberg who salvaged a front row starting spot with the last lap of the top-ten shootout action.
Hamilton?s success brought him his 10th pole position of the season and the 59th of his career.
?It?s always so tough trying to pull out the perfect laps when it matters,? said a relieved Hamilton. ?Definitely, for me, very challenging.?
Hamilton is 26 points behind Rosberg in the title chase with three races left.
If the German wins on Sunday and Hamilton scores just one point or fewer then Rosberg will be world champion for the first time.
Dutchman Max Verstappen looked sure to take second until Rosberg?s final fastest effort and he wound up third for Red Bull ahead of his team-mate Australian Daniel Ricciardo.
?It?s the front row and I am glad of that,? said Rosberg. ?I?m not on pole, but I have a chance from there. I don?t know why I have struggled to tune in the car, but I am there now. It was a brilliant lap by Lewis. I put it together when it counted."
The Red Bull pair will start Sunday?s race on super-soft tyres while the Mercedes men will be on ordinary softs, a strategic decision that may create a dramatic opening lap at the Autodromo Hermanos Rodriguez.
Nico Hulkenberg also delivered a spectacular late lap to take fifth place for Force India ahead of Kimi Raikkonen and four-time champion Sebastian Vettel of Ferrari.
Valtteri Bottas was eighth ahead of his Williams team-mate Felipe Massa and Carlos Sainz who was 10th for Toro Rosso.
On a bright, but cool day at the Autodrom Hermanos Rodriguez, Briton Jolyon Palmer was ruled out of qualifying shortly before it began because Renault had discovered a crack in his chassis.
The team planned to build up a new car for him to race on Sunday, starting from the back of the grid.
When the action started, Hamilton was one of the first of the leading men into the fray for Q1. He was soon fastest before Vettel and Raikkonen clocked quicker times with their early laps, but responded to top the pack.