nginx redirect loop, remove index.php from url

2019-01-07 13:41发布

I want any requests like http://example.com/whatever/index.php, to do a 301 redirect to http://example.com/whatever/.

I tried adding:

rewrite ^(.*/)index.php$ $1 permanent;

location / {
    index  index.php;
}

The problem here, this rewrite gets run on the root url, which causes a infinite redirect loop.

Edit:

I need a general solution

http://example.com/ should serve the file webroot/index.php

http://example.com/index.php, should 301 redirect to http://example.com/

http://example.com/a/index.php should 301 redirect to http://example.com/a/

http://example.com/a/ should serve the index.php script at webroot/a/index.php

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.

标签: nginx php
4条回答
等我变得足够好
2楼-- · 2019-01-07 14:11

Try that

location ~ /*/index.php {
    rewrite ^/(.*)/(.*) http://www.votre_domaine.com/$1 permanent;
}
location /index.php {
    return 301 http://www.example.com/;
}
查看更多
小情绪 Triste *
3楼-- · 2019-01-07 14:19

Great question, with the solution similar to another one I've answered on ServerFault recently, although it's much simpler here, and you know exactly what you need.

What you want here is to only perform the redirect when the user explicitly requests /index.php, but never redirect any of the internal requests that end up being served by the actual index.php script, as defined through the index directive.

This should do just that, avoiding the loops:

server {
    index index.php;

    if ($request_uri ~* "^(.*/)index\.php$") {
        return 301 $1;
    }

    location / {

        # ...
    }
}
查看更多
够拽才男人
4楼-- · 2019-01-07 14:28

Keep the first slash out of the match :

rewrite ^/(. +)/index.php$ $scheme://$1/ permanent;
查看更多
再贱就再见
5楼-- · 2019-01-07 14:32

Try

location = /whatever/index.php {
    return 301 $scheme://www.example.com/whatever/;
}

Another benefit from doing it this way is that nginx does a return faster than a rewrite.

查看更多
登录 后发表回答