title: ASP.NET MVC behind NGINX reverse proxy
body: <p>I am currently working on a project that requires one of our current ASP.NET MVC5 web applications to sit behind a NGINX reverse proxy that the client will control.</p>
  
  <p>I am brand new to NGINX so am lacking in knowledge.</p>
  
  <p>The reverse proxy will be placed at a sub path. (example below)</p>
  
  <p><a href="http://localhost:9999/foo/bar/" rel="noreferrer">http://localhost:9999/foo/bar/</a></p>
  
  <p>This will then proxy to the root of the MVC5 application (port 9998) I have set up NGINX locally to test that the site will work as expected. We use absolute paths to our resources (hosted in an internal CDN) so all these load as expected.</p>
  
  <p><strong>My Issue</strong> - The reverse proxy is working correctly and displaying the root page of the application. The problems start to arise when hitting any controller methods/page links that have been created using this.RedirectToAction() or @html.ActionLink() etc. </p>
  
  <p>The MVC application does not realise it is running behind a reverse proxy and chops that subpath out of its derived URL. </p>
  
  <p>So a redirect to a home controller looks like </p>
  
  <p><strong><a href="http://localhost:9999/home" rel="noreferrer">http://localhost:9999/home</a></strong></p>
  
  <p>Instead of :</p>
  
  <p><strong><a href="http://localhost:9999/foo/bar/home" rel="noreferrer">http://localhost:9999/foo/bar/home</a></strong></p>
  
  <p>Does anyone have any ideas the counteract this? I can see .NET core has a workaround but cant see anything for MVC5. I can use this.Redirect() and specify the absolute path but the application is large and used in other scenarios without the reverse proxy.</p>
  
  <p>Can this be resolved through my NGINX configuration? I have included my config below :</p>
  
  <pre><code>#user  nobody;
  worker_processes  1;
  
  events {
  worker_connections  1024;
  }
  
  http {
  include       mime.types;
  default_type  application/octet-stream;
  sendfile        on;
  
  
  keepalive_timeout  65;
  
  server {
      listen       9999;
      server_name  localhost;
  
      location /foo/bar/ {
  
          rewrite ^/foo/bar/(.*)$ /$1 break;
          proxy_pass  http://127.0.0.1:9998/;
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      }
  
  }
  }
  </code></pre>