如何使用 Nginx 部署 Next.js 静态导出?(深层链接不起作用)

ors*_*zky 7 nginx next.js

我将 next.js 导出到该out文件夹​​中。

文件夹结构为:

  • 出去
    • 索引.html
    • 条款.html
    • 隐私.html

我设置 nginx 来提供此文件夹中的文件:

server {
    root /var/www/myproject/out;
    index index.html index.htm index.nginx-debian.html;

    server_name myproject.com;

    location / {
        try_files $uri $uri/ /index.html;
    }
}
Run Code Online (Sandbox Code Playgroud)

主页(索引)打开正常。从应用程序内导航到 url 等myproject.com/privacy效果很好。问题是,如果我尝试直接打开这些链接,它将提供主页(索引)而不是实际页面,因为这些 url 不存在于文件夹中。直接打开隐私页面的唯一方法是将 html 扩展名添加到 url: myproject.com/privacy.html

如何配置 nginxmyproject.com/privacy.html在有人输入myproject.com/privacyurl 时提供实际页面服务?

小智 14

问题是在try_files.

当前配置包括:

  • / (默认路由到根路径下的index.html)
  • 索引.html
  • /index.html
  • 测试/*.html

要访问不带扩展名的页面路由路径名,即,/privacy该格式应包含在try_filesinsdie中location /

尝试这个:

try_files $uri $uri.html /$uri /index.html
Run Code Online (Sandbox Code Playgroud)


Ron*_*omb 5

由于 NextJS 在 url 中处理 ids 的方式,我需要第二个位置块。NextJS 将有类似的文件[id].html或其他文件。

    location / {
        try_files $uri $uri.html /$uri /index.html;
    }

    location ~* /(.*)/(\d+)$ {
        try_files $1/[id].html /$1/[id].html /index.html;
    }
Run Code Online (Sandbox Code Playgroud)

所以我需要第二个块来捕获表单的 url/whatever/etc/5并将 nginx 重定向到/whatever/etc/[id].html