Fixing nginx links that have the wrong hostname or port

Is your nginx incorrectly redirecting to http://localhost:{some-port}? Read on for why it does this and how to fix it.

Tom van Neerijnen
localhost.run

--

Nginx helpfully tries to fully qualify all the links it generates. What does this mean? Say you store your “FAQ” sections html files in a directory called /var/www.html/faq . Because this is a directory you should link to https://yoursite/faq/in your other html files to serve up the index.html in there, but often in html we’ll link to https://yoursite/faqwithout the trailing /. When nginx sees a request without a slash that is served by a directory it helpfully returns a redirect with the slash in, using a HTTP location header.

If nginx is receiving the traffic directly from clients this is fine, but often it is behind a port forwarder like https://localhost.run, or a load balancer, and it runs on a non-standard port. In these cases your redirects can end up breaking and a request to https://yoursite/faqwill see your browser taking you to an address like http://localhost:8080/faq/ and returning an error, because http://localhost:8080 is where nginx is listening.

It’s possible to configure nginx to use the correct fully qualified domain name and port, but often it’s simpler to tell nginx to use relative redirects. This has the advantage of working the same no matter where your nginx gets deployed to. To do this, set absolute_redirect off; in the server declaration of your nginx.conf .

A complete example looks like this:

events {
worker_connections 512;
}
http {
server {
listen 8080 default_server;
absolute_redirect off;
root /var/www/html; index index.html
server_name _;
}
}

You can try this nginx configuration instantly with localhost.run by running ssh -R 80:localhost:8080 ssh.localhost.runin a terminal now , because localhost.run uses your already installed ssh client no signup or signin is required.

--

--