title: Handling flask url_for behind nginx reverse proxy
body: <p>I have a flask application using nginx for a reverse proxy/ssl termination, but I'm running into trouble when using url_for and redirect in flask.</p>
  
  <p>nginx.conf entry:</p>
  
  <pre><code>location /flaskapp {
    proxy_pass http://myapp:8080/;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
  </code></pre>
  
  <p>The idea is that a user navigates to </p>
  
  <p><code>https://localhost:port/flaskapp/some/location/here</code></p>
  
  <p>and that should be passed to flask as </p>
  
  <p><code>http://localhost:8080/some/location/here</code></p>
  
  <p>This works reasonably well when navigating to a defined route, however if the route has <code>redirect(url_for('another_page'))</code>, the browser is directed to </p>
  
  <p><code>http://localhost:8080/another_page</code></p>
  
  <p>And fails, when the URL I actually want to go to is: </p>
  
  <p><code>https://localhost:port/flaskapp/another_page</code></p>
  
  <p>I have tried several other answers for similar situations, but none have seemed to be doing exactly what I am doing here. I have tried using <code>_external=True</code>, setting <code>app.config['APPLICATION_ROOT'] = '/flaskapp'</code> and many iterations of different <code>proxy_set_header</code> commands in <code>nginx.conf</code> with no luck.</p>
  
  <p>As an added complication, my flask application is using <code>flask-login</code> and CSRF cookies. When I tried setting <code>APPLICATION_ROOT</code> the application stopped considering the CSRF cookie set by <code>flask-login</code> valid, which I assume has something to do with origins.</p>
  
  <p>So my question is, how do I make it so that when flask is returning a <code>redirect()</code> to the client, nginx understands that the URL it is given needs <code>flaskapp</code> written into it?</p>