【问题标题】:nginx config with spa and subdirectory root带有 spa 和子目录根的 nginx 配置
【发布时间】:2017-05-21 14:40:41
【问题描述】:

我似乎总是对 nginx 配置有问题。我的 SPA 位于 /mnt/q/app(已启用推送状态),前端根位于 client/public。一切都应该映射到 index.html,应用程序会在其中选择路线并决定要做什么。

索引的完整路径是/mnt/q/app/client/public/index.html。

我想我现在已经没有选择了。不管我做什么,我只是从 nginx 得到一个 404,我认为配置很简单,不知道出了什么问题。

server {
    listen 80;
    server_name app.dev;

    root /mnt/q/app;

    location / {
      root /client/public;
      try_files $uri @rewrites =404;
    }

    location @rewrites {
       rewrite ^(.+)$ /index.html last;
    }
}

感谢任何帮助。

【问题讨论】:

    标签: nginx single-page-application aurelia


    【解决方案1】:

    如果nginx 从根目录查看文件系统,则应将root 设置为/mnt/q/app/client/public,而不是您使用的两个值中的任何一个。

    try_files 指令的最后一个元素可以是默认操作(例如 /index.html)、命名位置或响应代码。您在倒数第二个元素中有一个命名位置 - 将被忽略。

    您的命名位置应该可以工作,但不是必需的,因为try_files 能够更简单地实现它。请参阅this document 了解更多信息。

    例如:

    root /mnt/q/app;
    
    location / {
        root /mnt/q/app/client/public;
        try_files $uri $uri/ /index.html;
    }
    
    location /api {
    }
    
    location /auth {
    }
    

    $uri/ 元素将在目录中添加一个尾随 /,以便 index 指令可以工作 - 如果您不需要它,则不必添加它。

    【讨论】:

    • 感谢您的回复。但是,我想在将来添加多个位置。例如,我将添加 api 和 auth 组件,我希望它们位于 /api 和 /auth,而路径应该位于 /mnt/q/app/api/ 和 /mnt/q/app/auth分别。我不确定我是否可以用这种方法做到这一点。我将此要点用作“模板”:gist.github.com/aotimme/5006831
    • 本地路径是通过将root 值与URI 连接形成的,因此/api 和/auth 块将使用相同的root 值(可以从外块)。我假设/index.html 是您问题中提到的文件的URI,它需要root 的不同值。查看更新。
    猜你喜欢
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 2021-05-26
    • 2020-07-22
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多