title: How to configure nginx X-Forwarded-Port to be the originally request port
body: <p>I am using nginx in a standard reverse proxy scenario, to pass all requests to <code>/auth</code> to another host, however I'm trying to use non-standard ports.</p>
  
  <p>My end goal is to have the <code>X-Forwarded-Port</code> header set to the port that the request comes in on.</p>
  
  <p>Here is my location block in nginx.conf:</p>
  
  <blockquote>
  <pre><code>location /auth/ {
      proxy_pass       http://otherhost:8090;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header X-Forwarded-Host $host;
      proxy_set_header X-Forwarded-Port &lt;VAR&gt;;
  }
  </code></pre>
  </blockquote>
  
  <p>This nginx is running in a docker container, that is configured to forward requests from 8085 into 80 in the container, such that the nginx process is listening on 80:</p>
  
  <blockquote>
    <p>0.0.0.0:8085->80/tcp</p>
  </blockquote>
  
  <p>When I hit the URL:</p>
  
  <blockquote>
    <p><a href="http://localhost:8085/auth/" rel="noreferrer">http://localhost:8085/auth/</a></p>
  </blockquote>
  
  <p>I am correctly redirected to <code>http://otherhost:8090</code>, but the <code>X-Forwarded-Port</code> header is missing or wrong.</p>
  
  <p>Where I have <code>&lt;VAR&gt;</code> in the original block, I have tried the following:</p>
  
  <ul>
  <li><p><code>$server_port</code> - This is the port nginx is listening on (80), not the
  request port.</p></li>
  <li><p><code>$pass_port</code> - Seems to be null in my setup, so nginx drops the
  header.</p></li>
  <li><p><code>$http_port</code> - This is a random port per request.</p></li>
  <li><p><code>$remote_port</code> - This is a random port per request.</p></li>
  </ul>
  
  <p>I <em>can</em> change my config at deploy time to hardcode  to the known port of incoming requests, but ideally I would be able to change the front port without any change to the nginx config.</p>
  
  <p>I've scoured <a href="http://nginx.org/en/docs/varindex.html" rel="noreferrer">the nginx variable list</a> but can't find anything like <code>$request_port</code>. Is there any way for me to achieve my intent?</p>