NextJS 部署到特定的 URL 路径

NextJS deploy to a specific URL path

我正在开发我的第一个 NextJS 应用程序。当我 运行 "npm run dev" 或 "npm run start" 时,它会将我的应用程序部署到

http://host:port/

当我导航到一个页面时,url 变成

http://host:port/page1

我需要有自己的具体URL,比如

http://host:port/my-test-application/path-for-my-app/
http://host:port/my-test-application/path-for-my-app/page1

此外,我的应用程序有很多元素 link 到应用程序的其他区域,我需要这些元素也可以使用 basePath 转到 URL 而不仅仅是转到根路径.

我还将把这个应用程序 depolying 到具有不同 basePaths 的不同服务器,因此不能在我的应用程序中进行硬编码。

我该怎么做?

对于 react/vue/angular/native JS 等其他应用程序,我只需构建我的应用程序并将构建代码放在我服务器上的 "my-test-application/path-for-my-app" 文件夹中。

我用我的 NextJS 应用程序试过这个,但我收到一个错误,提示找不到“.next”文件夹。

我用谷歌搜索并找到了一些关于使用 "assetPrefix" 或使用 "Zones" 的参考资料。但是我真的不明白我应该做什么。

如何将我的应用程序部署到特定 URL

解决方案 1:重组 "pages" - 不允许我部署到具有不同 basePaths 的不同服务器

我可以在我的 "pages" 目录中创建文件夹结构并更改我的所有元素以使用此文件夹结构。

|- pages
     |- my-test-application
           |- path-for-my-app
                |- index.js
                |- page1.js


<Link href="/my-test-application/path-for-my-app/page1" >

我不喜欢这个解决方案,因为 basePath 被硬编码到我的应用程序中,与部署设置相对应。

如果我想在具有不同 basePaths(即下面)的 2 个服务器上部署我的应用程序,我将必须有 2 个版本的代码。

http://host:port/my-test-application_1/path-for-my-app/page1
http://host:port/my-test-application_2/diff-path-for-my-app/page1

更新:我在 3 月 5 日更新了这个问题,包括我对 s 工作的需求和一个我不喜欢的解决方案。

您可以使用自定义服务器在您的特定 URL:

上创建 NextJS 应用程序

查看示例:

https://github.com/zeit/next.js/tree/canary/examples/custom-server-express

关键是将您的特定 url 添加为 API,然后将用户请求转发到您要提供服务的特定页面:

const express = require('express')
const next = require('next')

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  const server = express()

  server.get('/my-test-application/path-for-my-app', (req, res) => {
    return app.render(req, res, '/index', req.query)
  })

  server.get('/my-test-application/path-for-my-app/page1', (req, res) => {
    return app.render(req, res, '/page1', req.query)
  })

  server.get('/posts/:id', (req, res) => {
    return app.render(req, res, '/posts', { id: req.params.id })
  })

  server.all('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(port, err => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

我找到了一个使用 NGINX 反向代理 URL 和基本路径的解决方案。

有用links

应用程序更改

依赖关系

  • next-images : 为了在使用反向代理时从 "public" 导入静态图像
  • @zeit/next-css : 为了使用样式表文件
  • 以及通常的 NextJS 依赖项

next.config.js

在您的应用程序的根目录添加一个 "next.config.js" 文件,以便您可以指定 "assetPrefix" 和 "publicRuntimeConfig.basePath"

  • assetPrefix : NextJS 在访问组件、样式表、页面等时使用
  • publicRuntimeConfig.basePath : 用于 s 所以指定添加到 link 的前缀,在使用 public images[= 时用于 "" 元素的 "src" 标签124=]

例子

const isProd = process.env.NODE_ENV === 'production'

// Enable importing of css stylesheets
const withCSS = require("@zeit/next-css");
const withImages = require('next-images');

/*
 * Gets the BASE_PATH from the command used to start this app.
 * If BASE_PATH is specified but it does not start with a "/" 
 * then add it. 
 */
function getBasePath() {
    var basePath = ''

    if (isProd && process.env.BASE_PATH){
        if (process.env.BASE_PATH.startsWith("/") ){
            basePath = process.env.BASE_PATH;
        } else {
            basePath = "/" + process.env.BASE_PATH;
        }
    } 

    console.log("getBasePath() : isProd = " + isProd);
    console.log("getBasePath() : basePath = " + basePath);

    return basePath
}

module.exports = withCSS(withImages({
    assetPrefix: getBasePath() ,

    publicRuntimeConfig: {
        basePath: getBasePath() ,
    },

}));

静态图片

使用 "next-images" 导入图像并在 的 src 标签中引用导入的对象

更改对静态图像(/public 文件夹中的那些)的任何引用,使其具有基本路径前缀。例如我的 "Footer" 组件有以下

import '../stylesheets/main.css';

import img1 from '../public/image_name1.png'
import img2 from '../public/image_name2.png'

export default class o extends React.Component {

    render(){
        var prefix = publicRuntimeConfig.basePath
        return  (
            <div >
                <a className="icon" href="http://www.image_name.com" >
                    <img src={img1} alt="image_name1"/>
                </a>
                <a className="icon" href="http://www.image_name2.com">
                    <img  src={img1} alt="image_name2"/>
                </a>
            </div>
        );
    }
}

注意:我尝试使用 publicRuntimeConfig.basePath 作为 src URL 的前缀(如下所示),但这在我的部署环境中不起作用(见下文) )

    import getConfig from 'next/config'
    const { publicRuntimeConfig } = getConfig()
    ...
    ...
    <a className="icon" href="http://www.image_name.com" >
        <img src={`${publicRuntimeConfig.basePath}/image_name1.png`} alt="image_name1"/>
    </a>

Links

更改您的 Link 以使用基本路径前缀,例如在我的 "Header" 组件中我有以下

import Link from 'next/link';
import '../stylesheets/main.css';

import getConfig from 'next/config'
const { publicRuntimeConfig } = getConfig()

const detailId1 = "banana"

const Header = () => (
    <div>
        <div>
            <Link href={`${publicRuntimeConfig.basePath || ''}/`}>
                <a className="linkStyle">Home</a>
            </Link>

            <Link href={`${publicRuntimeConfig.basePath || ''}/about`} >
                <a className="linkStyle">About</a>
            </Link>

            <Link href={`${publicRuntimeConfig.basePath || ''}/details/[id]`} 
                  as= {`${publicRuntimeConfig.basePath || ''}/details/${detailId1}`} >
                <a className="linkStyle">Details Var 1</a>
            </Link>
        </div>
  </div>
);

export default Header;

注意:在博客 https://levelup.gitconnected.com/deploy-your-nextjs-application-on-a-different-base-path-i-e-not-root-1c4d210cce8a 中,它包含一个 "Link.tsx" 为您添加前缀,因此您只需使用那个 Link 组件(从“./Link.tsx”导入 Link;)而不是 nextJS 版本(从 'next/link' 导入 Link;)。但是,当我的 link URLs.

中有变量时,"Link.tsx" 对我不起作用

运行 你的 nextjs 应用程序

当 运行在本地安装您的应用程序而您不需要基本路径时,您可以 运行安装

npm run dev

由于没有指定 BASE_PATH 您的应用程序应该可以从“http://localhost:3000" and your src values should be "/image_name1.png" and when you hover over your s you will see the link is "http://localhost:3000/pagename”访问

如果您想 运行 使用基本路径,请执行以下操作

export BASE_PATH=a/b
npm run dev

注意:出于某种原因,在我的环境中,如果我指定 "export BASE_PATH=/a/b"(/ 在路径的开头),我会在路径的开头添加一个文件夹目录。因此我指定它时没有开始 / 并且 next.config.js 中的代码添加了开始 / 如果需要的话。

您无法在“http://localhost:3000”访问您的应用程序,因为您设置了基础 path/assetPrefix/publicRuntimeConfig.basePath。现在你需要一个反向代理。

NGINX:反向代理

我发现最简单的设置是使用 NGINX docker 图像。您需要 运行 NGINX 的配置包含重定向到您的 NextJS 应用程序。

创建一个文件夹并在该文件夹中添加一个 "default.conf" 文件。确保您在 "location" 中输入的路径与您在启动 nextjs 应用程序时为 BASE_PATH 指定的路径相同。

server {
    listen 80;
    server_name  localhost;

    location /a/b/ {
        proxy_pass http://myhost:3000/;
    }       
}

重要提示:

  • 您必须在 proxy_pass URL 的末尾添加尾随 / 否则其他路径不会传递到您的 NextJS 应用程序
  • 如果您在该位置使用变量,则必须确保包含传递路径

例子

location ~ /a/b/(.*)$ {  
    set $upstream http://myhost:3000/;
    proxy_pass $upstream;
}

在该目录的命令提示符中 运行 一个 NGINX docker 图像,告诉它使用您的配置文件。

docker run --name mynginx1 -v C:/zNGINX/testnginx/conf:/etc/nginx/conf.d -p 80:80 -d nginx
  • docker 容器的名称是 "mynginx1"
  • v 参数告诉它将计算机上 "C:/zNGINX/testnginx/conf" 中的所有文件复制到 docker 容器中的“/etc/nginx/conf.d”目录。这会将您的 "default.conf" 复制到 docker 容器,NGINX 将读取该配置文件。
  • 注意:请确保您的 docker 位置(“:/etc/nginx/conf.d”)的路径中有 "conf.d",我阅读的博客不包括这部分,它只指定了“:/etc/nginx/”,没有它图像就不会启动。
  • p 参数告诉 运行 端口 80 上的 NGINX

前往以下URL

http://localhost:80/a/b/

NGINX 会将 URL 重定向到“http://localhost:3000”。因此,现在应该可以使用基本路径从 URL 访问您的应用程序。单击 s 应该有效,link 应该包含转到 NGINX 的基本路径,NGINX 重定向回应用程序,剥离基本路径,留下任何其他路径。

真实世界服务器部署使用Docker

如果您将应用程序部署到服务器,而不是在本地 运行ning,您可以构建您的应用程序,然后将相关的 files/folders 复制到服务器计算机。确保在构建和 运行 应用程序

时设置了 BASE_PATH
export BASE_PATH=a/b
npm run build

cp package*.json [server_location]
cp next.config.js [server_location]
cp ./next [server_location]

然后在该服务器位置 运行

npm install
export BASE_PATH=a/b
npm run start   

注意:如果您在应用程序中引用了 "public" 中的图像,请使用 "next-images" 并导入图像,而不是使用 publicRuntimeConfig.basePath 作为字首。当我做后者时,找不到图像。有关示例,请参阅有关图像的部分。

我是这样解决的,在next.config.js中写了一个重定向:

const withImages = require('next-images')

module.exports = withImages(withSass({
    cssLoaderOptions: {
      url: false
    },
    //Might need to change it here, before going to the production environment.
    assetPrefix: 'http://localhost:3000',
    postcssLoaderOptions: {
      config: {
        ctx: {
          theme: JSON.stringify(process.env.REACT_APP_THEME)
        }
      }
    }
})); 

在 Next.js ≥ 9.5, you can set a basePath 在你的 next.config.js。例如,如果您希望整个 Next.js 应用在 /docs 上运行,您可以使用:

// next.config.js
module.exports = {
  basePath: '/docs'
}

Next 将确保从正确的位置提供所有资产,它会自动为您应用中的所有 Link 添加此基本路径的前缀,以及在使用 [=17= 的编程导航期间].例如,

<Link href="/about">
  <a>About Page</a>
</Link>

将转换为 link 到 /docs/about

router.push('/about')

这意味着您可以更改 basePath 而无需更改应用的实际代码中的任何内容。

要在此处添加答案,仅使用 basePath 是不够的。 basePath 非常适合自动指向链接,但它对 public 目录提供的静态文件没有任何作用。

例如,您在 imgImage 元素中将 public/img/my-img.png 称为 <img src="img/my-img.png" /><Image src="/img/my-img.png" />,您必须将其更改为分别为 <img src="your-sub-path/img/my-img.png" /><Image src="/your-sub-path/img/my-img.png" />

对我来说,所有提到的解决方案对我来说都太麻烦了,所以我采用了以下方式。

next.config.js

module.exports = {
  basePath: '/drh',
}

_app

您可以覆盖 _app.js 文件。

export default function App({ Component, pageProps }) {
  return <Component {...pageProps} base="/drh" />
}

这样所有页面都会有一个道具 base 硬编码。

export default function Index({ base }) {
  return <img src={`${base}/images/hooks-logo.png`}/>
}

上下文

如果您不想使用道具将此 base 推送给所有 children,您可以在此处使用 context。上下文提供程序也可以在 _app.js 中设置。

在我看来,nextjs 应用程序的一个很好的切入点是 _app.js,而典型的 React 应用程序是 index.js.