Rails app redirects to wrong port?

Ran into a situation in which a rails application was redirecting to /login to force a user to log in, but the Location header said “http://site.com:8085/login”, because nginx was listening on port 8085 on that server. At first I looked to see if there was something in the application code that was doing this, or maybe some setting I could change to fix it, but came up blank. After some Googling I found the answer right in the Nginx docs (below is my slightly-modified solution that handles https urls as well):

   proxy_redirect ~^(http(s?)://[^:]+):d+(/.+)$ $1$3;

That simply removes the port number from the Location: header, so whatever kind of proxy magic you’re doing will “just work.”