【问题标题】:NGINX try_files FallbackNGINX try_files 后备
【发布时间】:2016-06-08 20:39:26
【问题描述】:

我有这个文件夹结构:

/document/root/
|-- main
`-- wishlist

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

我不想为我根目录下的每个文件夹编写位置规则,所以我希望它尽可能通用。我找到了this 问题,它帮助我完成了大部分工作,但有些东西不起作用:如果我将浏览器指向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;
     }
}

【问题讨论】:

    标签: http nginx server


    【解决方案1】:

    保持简单:

    server {
        root /document/root/main/;
        index index.html;
    
        location /wishlist {
            root /document/root/;
        }
    }
    

    【讨论】:

      【解决方案2】:

      原来我找到了一种对我有用的方法:在 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 :) 希望这对其他人有所帮助。

      【讨论】:

        【解决方案3】:

        你需要为索引文件做的就是:

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

        【讨论】:

        • 感谢@Rob 的回答,但我还有其他文件夹(将来我会添加更多文件夹),我不想每次都编辑 nginx 文件我添加了一个新文件夹。这就是为什么我宁愿使用通用位置块而不是多个位置块。
        • @FilipeKiss 索引文件是它所在目录的索引。您不能拥有多个。所以每个目录都需要有自己的块,其中会有一个索引。
        • 哦,我明白了。因此,无论如何我都需要多个块作为索引。感谢您的解释。 :)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 2013-12-23
        • 2014-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多