title: Redundant Nginx Location and Rewrite Regular Expression
body: <p>I have a location and rewrite directive pair that works, but there is a redundancy that it seems like I should be able to optimize out.  It takes an external URL like <code>/css/20141201-styles.css</code> and delivers <code>/css/styles.css</code>.</p>
  
  <pre><code>location ~ '^/(css|js)/[0-9]{8}-' {
      rewrite '^/(css|js)/[0-9]{8}-(.*)$' /$1/$2;
  }
  </code></pre>
  
  <p>It seems like I'm doing work twice, once in matching, and then again when rewriting. Is there a way to capture the matches in the <code>location</code> directive, and then use them in the <code>rewrite</code>?</p>
  
  <pre><code>location ~ '^/(css|js)/[0-9]{8}-(.*)$' {
      rewrite [something here?] /$1/$2;
  }
  </code></pre>
  
  <p>In Apache, it looks like this:</p>
  
  <pre><code>RewriteRule ^/(css|js)/[0-9]{8}-(.*)$ /$1/$2 [NC,L]
  </code></pre>
  
  <hr>
  
  <p><strong>SOLUTION</strong></p>
  
  <p>Thanks to <a href="https://stackoverflow.com/users/4347203/terra">Terra</a> for pointing out the <code>alias</code> directive! This <code>location</code> was already nested in another <code>location</code> which applies the <code>root</code> directive, so that takes care of the server path.</p>
  
  <pre><code>location ~ ^/(css|images|js)/ {
      location ~ '^/(css|js)/[0-9]{8}-(.*)$' {
          alias /$1/$2;
      }
      root /server/path/to/web/root;
  }
  </code></pre>
  
  <p><strong>UPDATE</strong></p>
  
  <p>This also works, and has fewer lines. The <code>break</code> flag on the <code>rewrite</code> directive prevents looping of the <code>server</code> level, making it <a href="https://codereview.stackexchange.com/q/73342/49814">just as performant</a> as the <code>alias</code> solution.</p>
  
  <pre><code>location ~ ^/(css|images|js)/ {
      rewrite '^/(css|js)/[0-9]{8}-(.*)$' /$1/$2 break;
      root /server/path/to/web/root;
  }
  </code></pre>