This paper is devoted to the Moser-Trudinger-Onofri inequality on smooth compact connected Riemannian manifolds. We establish a rigidity result for the Euler-Lagrange equation and deduce an estimate of the optimal constant in the inequality on two-dimensional closed Riemannian manifolds. Compared to existing results, we provide a non-local criterion which is well adapted to variational methods, introduce a nonlinear flow along which the evolution of a functional related with the inequality is monotone and get an integral remainder term which allows us to discuss optimality issues. As an important application of our method, we also consider the non-compact case of the Moser-Trudinger-Onofri inequality on the two-dimensional Euclidean space, with weights. The standard weight is the one that is computed when projecting the two-dimensional sphere using the stereographic projection, but we also give more general results which are of interest, for instance, for the Keller-Segel model in chemotaxis.2010 Mathematics Subject Classification. Primary: 58J35, 58J05, 53C21; Secondary: 35J60, 35K55.