title: Nginx Reverse Proxying to Node.js with Rewrite
body: <p>I have several apps running behind an Nginx reverse proxy, one of which is a Node server with Express.js. I'm proxying <code>domain.com/demo/app/&lt;path&gt;</code> to <code>localhost:7003/&lt;path&gt;</code> using this Nginx config:</p>
  
  <pre><code>http {
  
      ...
  
      server {
  
          listen 80;
          server_name domain.com;
  
          ...
  
          location /demo/app {
  
              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-Scheme $scheme;
  
              rewrite ^/demo/app/?(.*) /$1 break;
              proxy_pass http://localhost:7003;
          }
  
          ...
      }
  }
  </code></pre>
  
  <p>This works great and <code>app</code> receives requests as if it was rooted at <code>/</code>. The problem is <code>app</code> handles its own static files and might make requests for routes such as <code>css/app.css</code> or <code>images/image.jpg</code>. But because of the reverse proxy, these actually exist at <code>/demo/app/css/app.css</code> and <code>/demo/app/images/image.jpg</code> respectively.</p>
  
  <p>I've solved this by getting Nginx to pass to Node a custom header indicating the root path, which the Node server prepends to the URLs of all subsequent requests. But now my code is littered with these root path strings. For example, part of my back-end templates:</p>
  
  <pre><code>link(rel='stylesheet', href="#{basePath}/css/base.css")
  link(rel='stylesheet', href="#{basePath}/css/skeleton.css")
  link(rel='stylesheet', href="#{basePath}/css/layout.css")
  </code></pre>
  
  <p>What's a more elegant way to handle this? Isn't there a way to get Nginx to recognize requests coming from an upstream server and automatically forward them to that server?</p>