Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

nginx redirect loop, remove index.php from url

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 / {

        # ...
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...