nginx重定向循环,从url中删除index.php

jca*_*ll1 24 php nginx

我想要任何请求,如http://example.com/whatever/index.php301进行重定向http://example.com/whatever/.

我尝试添加:

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

location / {
    index  index.php;
}
Run Code Online (Sandbox Code Playgroud)

这里的问题是,这个重写在根URL上运行,导致无限重定向循环.

编辑:

我需要一个通用的解决方案

http://example.com/ 应该提供文件 webroot/index.php

http://example.com/index.php,应该301重定向到 http://example.com/

http://example.com/a/index.php 应该301重定向到 http://example.com/a/

http://example.com/a/ 应该服务于index.php脚本 webroot/a/index.php

基本上,我从不想在地址栏中显示"index.php".我有旧的反向链接,我需要重定向到规范的网址.

cns*_*nst 60

很好的问题,解决方案类似于我最近在ServerFault上回答的另一个解决方案,虽然它在这里更简单,但你确切知道你需要什么.

您在此处想要的是仅在用户明确请求时执行重定向/index.php,但从不重定向任何最终由实际index.php脚本提供服务的内部请求,如通过index指令定义的那样.

这应该做到这一点,避免循环:

server {
    index index.php;

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

    location / {

        # ...
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案.我想知道如果没有`if(){}`语法而不是一个班轮怎么办呢?无论如何,现在,我修改了一下以保留查询字符串,如果有的话:`if($ request_uri~*"^(.*/)index\.php(?:.*)$"){``return 301 $ 1 $ is_args $ args;``}` (5认同)
  • 好的@Neo为了避免双斜线//我改变了一点#Strip index.php以避免重复内容`if($ request_uri~*"^(.*/)index\.php(/?)(.*) "){return 301 $ 1 $ 3; }` (4认同)
  • 我认为应该允许传递查询参数.将其更改为:if($ request_uri~*"^(.*/)index\.php(.*)"){return 301 $ 1 $ 2; } (3认同)