--- title: 静态托管部署 description: 不使用 Docker 时,用 nginx / 对象存储 / CDN 托管静态产物 outline: deep --- # 静态托管部署 适用:已有 nginx / Apache / Caddy,或使用对象存储 / CDN,不想引入 Docker。 核心流程只有两步:**构建产物** → **托管静态文件**。 ## 编译产物 ```bash npm ci npm run build # 产物在 .vitepress/dist ``` 本地验证构建结果(不要用于生产): ```bash npm run preview # http://127.0.0.1:4173/docs/ ``` ## nginx:子路径挂载(推荐) 把产物放到一个 `docs` 子目录,即可与 `base` 天然对齐,**无需 alias**: ```bash sudo mkdir -p /var/www/iotlcm/www sudo cp -r .vitepress/dist /var/www/iotlcm/www/docs ``` ```nginx server { listen 80; server_name _; root /var/www/iotlcm/www; location /docs/ { try_files $uri $uri.html $uri/ $uri/index.html =404; } location = /docs { return 301 /docs/; } } ``` 此处 `root` 指向父目录、产物在 `docs/` 子目录下,`/docs/assets/app.js` 会自然映射到 `/var/www/iotlcm/www/docs/assets/app.js`,不需要 `alias`。 ## nginx:根路径独占域名 若文档站独占一个域名、需要挂在 `/`,必须**改 `base` 后重新构建**: ```bash sed -i "s#base: '/docs/'#base: '/'#" .vitepress/config.mts npm run build ``` ```nginx server { listen 80; server_name docs.example.com; root /var/www/iotlcm-docs; index index.html; location / { try_files $uri $uri.html $uri/ =404; } } ``` ::: danger 不要只改服务器配置 `base` 与访问前缀必须一致。改了 nginx 却不改 `base`(或反之),一定会白屏。详见 [路径前缀必读](./path-prefix)。 ::: ## Apache 需要启用 `mod_rewrite`,用 `.htaccess` 做 cleanUrls 映射: ```apache RewriteEngine On RewriteBase /docs/ # 已存在的文件/目录直接返回 RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] # 无后缀路径映射到 .html 或 index.html RewriteCond %{REQUEST_FILENAME}.html -f RewriteRule ^(.+)$ $1.html [L] RewriteCond %{REQUEST_FILENAME}/index.html -f RewriteRule ^(.+)$ $1/index.html [L] ``` 产物目录放置方式与 nginx 子路径方案一致:`/var/www/html/docs/`。 ## Caddy Caddy 配置更简洁,`try_files` 语义与 nginx 类似: ```caddyfile example.com { handle_path /docs/* { root * /var/www/iotlcm-docs try_files {path} {path}.html {path}/index.html file_server } } ``` 或产物放在子目录、不做前缀处理: ```caddyfile example.com { root * /var/www/iotlcm/www try_files {path} {path}.html {path}/index.html file_server } ``` ## 对象存储 / CDN 产物是纯静态文件,可直接上传到 S3 / OSS / MinIO 等: ```bash npm run build # 上传 .vitepress/dist 全部内容到桶内 docs/ 前缀下 ``` 要点: - 上传时保持 `/docs/` 前缀(或改 `base` 后重新构建) - 配置**默认首页**为 `docs/index.html` - 配置 **404 页面**为 `docs/404.html`(产物已自带) - `cleanUrls: true` 意味着页面 URL 不带 `.html`,需对象存储支持「无后缀映射到 .html」,否则需关闭 `cleanUrls` 重新构建 ::: tip 关闭 cleanUrls 若对象存储不支持无后缀映射,编辑 `.vitepress/config.mts` 把 `cleanUrls: true` 改为 `false`,重新构建后页面 URL 会带 `.html` 后缀。 ::: ## pnpm / yarn 仓库同时提供 `package-lock.json` 与 `pnpm-lock.yaml`。使用 pnpm: ```bash pnpm install --frozen-lockfile pnpm run build ``` npm 与 pnpm 二选一即可,**不要混用**(会产生不一致的 `node_modules`)。