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.”

Putting up a "down for maintenance" message using mod_rewrite

Putting this here for safekeeping so my future self can find it. Mod_rewrite is one of my favorite tools, but it’s easy to spend 30 minutes crafting a 2-line directive that actually does what you want. I put this in a .htaccess file in the DocumentRoot of the server, put a “We’re down” message in maintenance.html (or whatever), and all requests will get a 302 redirect to /maintenance.html, except requests for /maintenance.html (for obvious reasons). It appends the original request in case you want to do something with it but that’s not really important. It also doesn’t do the redirect for images/js/css so those can actually be used in the maintenance message.

RewriteEngine on
RewriteRule ^maintenance.html	-	[PT,L]

RewriteCond %{REQUEST_URI}	!(gif|jpg|css|js)$
RewriteRule (.*) /maintenance.html?redir=true&originalRequest=%{REQUEST_URI} [R=302]

Putting up a “down for maintenance” message using mod_rewrite

Putting this here for safekeeping so my future self can find it. Mod_rewrite is one of my favorite tools, but it’s easy to spend 30 minutes crafting a 2-line directive that actually does what you want. I put this in a .htaccess file in the DocumentRoot of the server, put a “We’re down” message in maintenance.html (or whatever), and all requests will get a 302 redirect to /maintenance.html, except requests for /maintenance.html (for obvious reasons). It appends the original request in case you want to do something with it but that’s not really important. It also doesn’t do the redirect for images/js/css so those can actually be used in the maintenance message.

RewriteEngine on
RewriteRule ^maintenance.html	-	[PT,L]

RewriteCond %{REQUEST_URI}	!(gif|jpg|css|js)$
RewriteRule (.*) /maintenance.html?redir=true&originalRequest=%{REQUEST_URI} [R=302]