title: nginx redirect loop, remove index.php from url
body: <p>I want any requests like <code>http://example.com/whatever/index.php</code>, to do a 301 redirect to <code>http://example.com/whatever/</code>.   </p>
  
  <p>I tried adding:</p>
  
  <pre><code>rewrite ^(.*/)index.php$ $1 permanent;
  
  location / {
      index  index.php;
  }
  </code></pre>
  
  <p>The problem here, this rewrite gets run on the root url, which causes a infinite redirect loop.  </p>
  
  <p>Edit:</p>
  
  <p>I need a general solution</p>
  
  <p><code>http://example.com/</code> should serve the file <code>webroot/index.php</code></p>
  
  <p><code>http://example.com/index.php</code>, should 301 redirect to <code>http://example.com/</code></p>
  
  <p><code>http://example.com/a/index.php</code> should 301 redirect to <code>http://example.com/a/</code></p>
  
  <p><code>http://example.com/a/</code> should serve the index.php script at <code>webroot/a/index.php</code></p>
  
  <p>Basically, I never want to show "index.php" in the address bar.  I have old backlinks that I need to redirect to the canonical url.  </p>