title: Rewrite within location with a new root/alias - Nginx
body: <p>My folder structure is as follows:</p>
  
  <pre><code>/www
      /api.domain.tld
      /app.domain.tld
  </code></pre>
  
  <p>The API contains the system it self and APP implements the API via HTTP.</p>
  
  <p>I want to create an Nginx server for app.domain.tld that also contains an "virtual directory" for API.</p>
  
  <p>You can contact the API likes this: <a href="http://api.domain.tld/method/api.json" rel="nofollow">http://api.domain.tld/method/api.json</a></p>
  
  <p>But it would be great if the API can be contacted like this also: <a href="http://app.domain.tld/api/method/api.json" rel="nofollow">http://app.domain.tld/api/method/api.json</a> without copying something into APP, but keep those two "systems" separated.</p>
  
  <p>What I have for now:</p>
  
  <pre><code>server {
      listen 80;
      root /var/www/app.domain.tld;
      index index.php index.html;
  
  
      server_name app.domain.tld;
  
  
      location ^~ /api {
          alias /var/www/api.domain.tld;
  
  
          location ~ \.php$ {
              try_files $uri = 404;
              fastcgi_pass unix:/var/run/php5-fpm.sock;
              fastcgi_index index.php;
              fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
              include fastcgi_params;
          }
  
  
          rewrite ^/api/([a-z]+)/api.json$ /api.php?method=$1 last;
      }
  
  
      location....
      location....
      location....
  
  
      location ~ \.php$ {
          try_files $uri = 404;
          fastcgi_pass unix:/var/run/php5-fpm.sock;
          fastcgi_index index.php;
          fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
          include fastcgi_params;
      }
  }
  </code></pre>
  
  <p>Unfortunately this does now works as expected.</p>
  
  <p>The rewrite does not work at all. I can get api.domain.tld/index.php but when it needs to use the rewrite, it will not work.</p>
  
  <p>I have tried several things. Either I get 404 or 403 with this error:
  directory index of [path] is forbidden</p>
  
  <p>Can someone come up with a better solution that actually works?</p>
  
  <p>Regards</p>