本文介绍如何将Next.js项目部署到IIS创建的网站。
前提条件
在部署网站之前,先要在Windows服务器上安装好IIS、Node.js和iisnode
然后在IIS创建相关网站:
具体步骤
开发机上使用命令在 npx create-next-app@latest --typescript 创建的Next.js项目目录结构如下:
在部署到服务器之前,运行 npm run build 命令来执行应用的构建。
然后在项目文件夹添加文件server.js,内容如下:
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const app = next({ dev: false });
const handle = app.getRequestHandler();
app.prepare().then(() =>
{
createServer((req, res) =>
{
// Be sure to pass `true` as the second argument to `url.parse`.
// This tells it to parse the query portion of the URL.
handle(req, res, parse(req.url, true));
}).listen(process.env.PORT);
});
接着在项目文件夹添加文件web.config,内容如下:
<configuration>
<system.webServer>
<handlers>
<add name="iisnode" path="server.js" verb="*" modules="iisnode" />
</handlers>
<rewrite>
<rules>
<rule name="myapp">
<match url="/*" />
<action type="Rewrite" url="server.js" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
也可以直接点击这里下载这两个文件,现在的项目文件是这样
其中选中的是需要上传到服务器的文件夹和文件。
然后把 .next、node_modules这两个文件夹和server.js、web.config这两个文件上传到服务器上已经创建好的网站目录,或者上传到我们的虚拟主机:
最后在浏览器中输入网站网址就可以打开网站。