title: Add URL Prefix to requests using nginx or rails
body: <p>I'm trying to understand the best way to redirect all traffic for <a href="https://app.company.com/" rel="nofollow">https://app.company.com/</a> to <a href="https://app.company.com/app" rel="nofollow">https://app.company.com/app</a></p>
  
  <p>app.company.com is a rails 4.2 server which uses nginx to serve static assets and unicorn to handle the rails requests.</p>
  
  <p>Should this redirect happen in nginx or rails?</p>
  
  <h1>Back story:</h1>
  
  <p>A few years ago I supported some rails apps that were installed on the intranet using URL Prefixing, like:</p>
  
  <pre><code>https://company.com/app1/
  https://company.com/app2/
  https://company.com/app3/
  </code></pre>
  
  <p>company.com ran an nginx server which routed traffic to each app server based on the url prefix.</p>
  
  <p>Each app server runs nginx to serve static assets and unicorn as the rails server.</p>
  
  <p>Recently a decision was made to hand management of the company.com server over to the parent company.  As a result, a decision was made to route to each rails server by DNS using subdomains in place of nginx rules.</p>
  
  <p>For now apps will be accessed using:</p>
  
  <pre><code>https://app1.company.com/app1/
  https://app2.company.com/app2/
  https://app3.company.com/app3/
  </code></pre>
  
  <p>Individual app servers are largely unchanged.  They still run nginx and unicorn.</p>
  
  <p>My main issue is understanding the best way to push traffic for the root to the url prefix</p>
  
  <pre><code>https://app1.company.com/  --&gt;  https://app1.company.com/app1/
  </code></pre>
  
  <p>The root route without the url prefix never reached the rails servers before.</p>
  
  <h1>UPDATE</h1>
  
  <p>Here is my nginx config file with original enhancement proposed by Vashed's answer.</p>
  
  <p>I'm now curious if there is a refinement to this which would allow my config file to be independent of the server name like it was before.</p>
  
  <pre><code>upstream unicorn {
    server unix:/tmp/unicorn.app1.sock fail_timeout=0;
  }
  
  server {
    listen 80 deferred;
  
    # ADDED THIS LOCATION BLOCK PER VASFED'S ANSWER
    location = / {
      rewrite ^ https://app1.company.com/app1;
    }
  
    location /app1/assets {
      alias /var/www/application/current/public/app1/assets;
    }
  
    # Serve file uploads from nginx
    location /app1/system {
      alias /var/www/application/current/public/app1/system;
    }
  
    try_files $uri $uri/ @unicorn;
  
    location @unicorn {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_redirect off;
      proxy_pass http://unicorn;
    }
  
    client_max_body_size 1G;
    keepalive_timeout 10;
  }
  </code></pre>