Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Http NGINX try\u文件回退_Http_Nginx_Server - Fatal编程技术网

Http NGINX try\u文件回退

Http NGINX try\u文件回退,http,nginx,server,Http,Nginx,Server,我有以下文件夹结构: /document/root/ |-- main `-- wishlist 我想让我的nginx这样工作:如果我将浏览器指向example.com/wishlist,它将在wishlist文件夹中显示index.html。如果我将浏览器指向example.com,我希望它返回到main/index.html(当然还有相关的main/style.css和主目录中的其他文件) 我不想为根目录下的每个文件夹编写位置规则,所以我希望它尽可能通用。我找到了Question,它帮助我

我有以下文件夹结构:

/document/root/
|-- main
`-- wishlist
我想让我的nginx这样工作:如果我将浏览器指向
example.com/wishlist
,它将在
wishlist
文件夹中显示
index.html
。如果我将浏览器指向
example.com
,我希望它返回到
main/index.html
(当然还有相关的
main/style.css
和主目录中的其他文件)

我不想为根目录下的每个文件夹编写位置规则,所以我希望它尽可能通用。我找到了Question,它帮助我完成了大部分工作,但有一点不起作用:如果我将浏览器指向
wishlist/index.html
,它会工作得很好。但是如果我删除
index.html
并将其指向
example.com/wishlist
浏览器将返回404。我当前的Nginx配置如下。有人能给我指出正确的方向吗?谢谢

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    root /document/root/main;

    location ~ ^/([^/]+)(/.+)?$ {
        if (!-d "$document_root/$1") {
            return 404;
        }
        try_files /$1$2 /main$2 =404;
     }
}

索引文件只需执行以下操作:

index index.html

location / {
    try_files $uri.html $uri/index.html =404;
}
location /wishlist {
    try_files $uri.html $uri/index.html =404;
}

结果我找到了一种适合我的方法:在nginx上使用自定义的
@location
。我的最后一段代码是这样的:

location / {
    root /document/root/main;
    index index.html;
    try_files $uri $uri/ index.html;
}


location ~ ^/(.+)$ {
    root /document/root;
    index index.html;
    try_files $uri $uri/ index.html @main;
}

location @main {
    try_files /main/$uri /main/$uri/;
}
现在
example.com
使用
/document/root/main
作为根,而
example.com/wishlist
使用
/document/root/wishlist
:)希望这能帮助其他人。

保持简单:

server {
    root /document/root/main/;
    index index.html;

    location /wishlist {
        root /document/root/;
    }
}

谢谢你的回答,@Rob,但我还有其他文件夹(将来我会添加更多文件夹),我不想每次添加新文件夹时都要编辑nginx文件。这就是为什么我宁愿使用一个通用位置块而不是多个。@FilipeKiss索引文件是它所在目录的索引。您不能有多个。所以每个目录都需要自己的块,在那里有一个索引。哦,我明白了。因此,不管怎样,我都需要多个块作为索引。谢谢你的解释。:)