【问题标题】:Is it possible to rewrite the route of a static .txt file in Next.js是否可以在 Next.js 中重写静态 .txt 文件的路由
【发布时间】:2022-12-17 22:51:33
【问题描述】:

我有一个 Next.js 应用程序,它在公共文件夹的根目录中有一个 robots-staging.txt 文件。我希望将其添加到 next.config 中的重写函数。这就是我所拥有的

async rewrites() {
    const rewriteList = [
      {
        source: '/robots-staging.txt',
        destination: '/robots.txt',
      },
    ];
    return rewriteList;
  },

我最初的期望是,当我点击 localhost:3000/robots.txt 时,这将提供暂存文件,但它不起作用。我错过了什么吗?

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    如果我理解正确,您想将 /robots.txt 代理到 /robots-staging.txt,则需要将后者设为目标而不是源。

    除此之外,我遇到了同样的问题,我不确定这是错误还是功能,但我发现使用绝对路径/URL 可以作为一种解决方法,因为相对路径似乎被解释为页面:

     async rewrites() {
          {
            source: "/robots.txt",
            destination:
              process.env.NODE_ENV === "development"
                ? "http://localhost:3000/robots-staging.txt"
                : "https://YOUR_URL/robots-staging.txt",
          },
        ];
      },
    

    【讨论】:

      【解决方案2】:

      我尝试了很多变化。这是唯一有效的方法:

      async rewrites() {
          return {   
            beforeFiles: [   
              {
                source: "/robots.txt",
                destination:
                  process.env.NEXT_ROBOTS_ENV === "production"
                    ? "/robots.txt"
                    : "/robots-staging.txt",
              },
            ]
          }
        },
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-18
        • 2022-01-04
        • 2020-05-19
        • 1970-01-01
        • 2022-11-12
        • 2020-10-12
        • 1970-01-01
        • 2021-07-11
        相关资源
        最近更新 更多