首页 > 解决方案 > 子文件夹根目录中的默认重定向未重定向到 index.php

问题描述

在根目录中,任何重定向localhost/都只是简单地重定向到 index.php,但是如果您进入localhost/phone子目录,也会有一个 index.php 页面,并且当您键入localhost/phone/时,您不会重定向到 index.php 页面。不知道为什么。这是我的服务器配置。

server {
        listen       80;
        listen       [::]:80 default_server;
        server_name  localhost;
        charset UTF-8;
        index index.html index.php;
        location / {
            root   xyz;
            proxy_set_header Connection "";
            if ($request_uri ~ ^/(.*)\.html$) {  return 302 /$1;  }
            try_files $uri $uri/ $uri.html $uri.php?$args;
            rewrite ^/(.*)/$ /$1 permanent;
            location ~*  \.(jpg|jpeg|png|gif|ico|css|js|ttf|webp)$ {
                expires 365d;
            }
       }

我试图指向目录并为 index.php 添加了默认值,它可以工作,但现在所有的 url/phone/都显示为空白。

location /phone {
   index index.html index.php;
}

“显示空白”表示根据错误日志显示 404 错误

2019/05/08 23:40:58 [error] 26240#14076: *1 CreateFile() "C:\xyz\nginx/xyz/phone/index" 失败(2:系统找不到指定的文件),客户端: ::1,服务器:本地主机,请求:“GET /phone/index HTTP/1.1”,主机:“本地主机”

现在 index.php 显示 404 错误,我做错了什么?即使文件在那里

标签: nginxredirect

解决方案


如果要避免/所有 URI 的尾随,但仍要测试index.htmland index.php,则应避免使用index指令和$uri/带有try_files指令的术语。

一种方法是使用命名位置来测试 PHP 文件。此位置将需要您的fastcgi配置。

例如:

root /path/to/root;

location / {
    if ($request_uri ~ ^/(.*)\.html$) { return 302 /$1; }
    rewrite ^/(.*)/$ /$1 permanent;

    try_files $uri $uri.html $uri/index.html @php;
}
location @php {
    try_files $uri.php $uri/index.php =404;
    fastcgi_pass ...;
    ...
}

推荐阅读