本地 TLS

本地 TLS

¥Local TLS

本指南目前仅适用于使用 Classic Remix 编译器 的情况。

在本地使用 HTTP 更简单,但如果你确实需要在本地使用 HTTPS,请按照以下步骤操作。

¥It's simpler to use HTTP locally, but if you really need to use HTTPS locally, here's how to do it.

remix-serve 不支持本地 HTTPS,因为它旨在成为一个帮助你快速上手的极简服务器。remix-serve 是 Express 的简单封装器,因此如果你想在本地使用 HTTPS,可以直接使用 Express。如果你运行 remix dev 时未使用 -c 标志,则隐式使用 remix-serve 作为应用服务器。

使用本地 TLS 运行应用服务器

¥Running your app server with local TLS

第一步是让你的应用服务器在本地 TLS 下运行,而不运行 remix dev。这将为你在下一节使用本地 TLS 设置 remix dev 时的成功做好准备。

¥The first step is to get your app server running with local TLS without running remix dev. That will set you up for success when you set up remix dev with local TLS in the next section.

👉 安装 mkcert

¥👉 Install mkcert

👉 创建本地证书颁发机构:

¥👉 Create a local Certificate Authority:

mkcert -install

👉 告诉 Node 使用我们的本地 CA:

¥👉 Tell Node to use our local CA:

export NODE_EXTRA_CA_CERTS="$(mkcert -CAROOT)/rootCA.pem"

👉 创建 TLS 密钥和证书:

¥👉 Create a TLS key and certificate:

mkcert -key-file key.pem -cert-file cert.pem localhost

如果你使用自定义主机名,则可以在生成 TLS 密钥和证书时将 localhost 更改为其他名称。

👉 使用 key.pemcert.pem 使 HTTPS 在你的应用服务器本地运行。

¥👉 Use the key.pem and cert.pem to get HTTPS working locally with your app server.

具体操作取决于你使用的应用服务器。例如,以下是如何在 Express 服务器上使用 HTTPS:

¥How you do this will depend on what app server you are using. For example, here's how you could use HTTPS with an Express server:

import fs from "node:fs";
import https from "node:https";
import path from "node:path";

import express from "express";

const BUILD_DIR = path.resolve(__dirname, "build");
const build = require(BUILD_DIR);

const app = express();

// ... code setting up your express app goes here ...

const server = https.createServer(
  {
    key: fs.readFileSync("path/to/key.pem"),
    cert: fs.readFileSync("path/to/cert.pem"),
  },
  app
);

const port = 3000;
server.listen(port, () => {
  // ... code to run after your server is running goes here ...
});

👉 使用本地 TLS 运行应用服务器

¥👉 Run your app server with local TLS

例如,使用上面的 Express 服务器,你可以像这样运行它:

¥For example, with the Express server above, you would run it like this:

remix build
node ./server.js

使用本地 TLS 运行 remix dev

¥Running remix dev with local TLS

首先,确保你可以在没有 remix dev 的情况下使用本地 TLS 运行你的应用!如果你还没有查看上一节,请查看它。

¥Make sure you can run your app with local TLS without remix dev first! Check out the previous section if you haven't done that yet.

👉 为 remix dev 启用 TLS

¥👉 Enable TLS for remix dev

通过配置:

¥Via config:

/** @type {import('@remix-run/dev').AppConfig} */
module.exports = {
  dev: {
    tlsKey: "key.pem", // relative to cwd
    tlsCert: "cert.pem", // relative to cwd
  },
};

或通过标志:

¥or via flags:

remix dev --tls-key=key.pem --tls-cert=cert.pem -c "node ./server.js"

你的应用现在应该正在使用本地 TLS 运行!

¥Your app should now be running with local TLS!

Remix v2.17 中文网 - 粤ICP备13048890号