Merge branch 'next' into develop

# Conflicts:
#	docs/docs/ru/get-started/deployment/production.md
#	packages/plugins/@nocobase/plugin-ai/src/client-v2/ai-employees/chatbox/utils.ts
#	packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/chatbox/Sender.tsx
#	packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/chatbox/hooks/useUploadFiles.ts
This commit is contained in:
Drol
2026-07-16 09:04:26 +08:00
248 changed files with 9167 additions and 635 deletions
+5
View File
@@ -59,6 +59,11 @@
"label": "附件字段",
"link": "/file-manager/field-attachment"
},
{
"type": "custom-link",
"label": "稳定 URL",
"link": "/file-manager/stable-url"
},
{
"type": "custom-link",
"label": "文件预览",
+146
View File
@@ -0,0 +1,146 @@
---
pkg: '@nocobase/plugin-file-manager'
title: "稳定 URL(代理 URL"
description: "介绍 NocoBase 文件稳定 URL 的格式、访问权限,以及它在附件字段、文件表、Markdown、文件预览和 HTTP API 中的表现。"
keywords: "稳定 URL,代理 URL,永久 URL,文件访问,文件权限,Office 预览,NocoBase"
---
# 稳定 URL
在 NocoBase 中,由存储引擎托管的文件会通过**稳定 URL(Stable URL**访问。这个地址先进入 NocoBase,再由 NocoBase 检查文件记录和访问权限,最后重定向到存储引擎生成的实际地址。
## URL 格式
文件记录返回的地址通常是:
```text
/files/<app>/<dataSource>/<collection>/<id><extname>
```
比如:
```text
/files/main/main/attachments/42.pdf
```
如果 NocoBase 配置了 `APP_PUBLIC_PATH=/nocobase`,地址会自动带上该前缀:
```text
/nocobase/files/main/main/attachments/42.pdf
```
其中:
- `app` 是应用名称
- `dataSource` 是数据源标识
- `collection` 是附件表或文件表名称
- `id` 是文件记录的 ID
- `extname` 是文件扩展名,没有扩展名时不会追加
文件创建后,`id``extname` 不允许修改,因此同一条文件记录的地址可以保持稳定。
## 不同用途的地址
同一条文件记录会根据用途使用不同的 query 参数:
| 用途 | 地址形式 | 表现 |
|---|---|---|
| 打开或内嵌文件 | `/files/.../42.pdf` | 检查权限后重定向到文件实际地址 |
| 预览图片等内容 | `/files/.../42.png?preview=1` | 检查权限后重定向到存储引擎的预览地址;存储引擎支持缩略图规则时会使用缩略图 |
| 下载文件 | `/files/.../42.pdf?download=1` | 检查权限后返回带下载语义的实际地址 |
| Office 在线预览 | `/files/.../42.xlsx?temporaryAccessToken=...` | 供 Microsoft Office Online Viewer 短期读取,不作为普通文件地址保存 |
:::tip
业务代码通常只需要使用接口返回的 `url``preview`,不需要自己拼接 `/files` 地址或 query 参数。
:::
## 在各个地方的表现
### 附件字段和文件表
附件字段与文件表中的系统托管文件,上传、查询和关联读取后返回的 `url` 都是稳定 URL`preview` 则是在同一地址上增加 `preview=1`
图片、PDF、音视频和文本等文件仍可在 NocoBase 中预览。刚上传的本地图片会优先使用浏览器生成的临时本地预览,数据重新读取后再使用稳定 URL,避免上传完成时出现重复请求或缩略图闪烁。
### HTTP API
通过 [HTTP API](./http-api.md) 上传或查询文件时,响应中的 `url` / `preview` 不再暴露本地路径、对象存储域名或预签名下载地址。调用方访问稳定 URL 时需要携带对应应用的登录凭证。
稳定 URL 返回 `302` 重定向,不直接代理文件流。如果使用 `curl` 等客户端读取文件内容,需要允许跟随重定向:
```bash
curl -L \
-H "Authorization: Bearer <JWT>" \
"https://example.com/files/main/main/attachments/42.pdf"
```
浏览器直接打开文件时通常使用登录 cookie。`GET``HEAD` 可以访问稳定 URL,其他 HTTP 方法会返回 `405`
### Markdown 编辑器
在 Markdown 编辑器中上传文件后,写入 Markdown 内容的是稳定 URL。私有 S3、OSS、COS 或 S3 Pro 存储也可以使用这种方式,不需要把存储空间调整为公开读取。
如果 Markdown 内容会展示在未登录页面,那么查看者仍需要拥有文件查看权限。仅把稳定 URL 写入 Markdown,不会自动把文件公开。
### 附件 URL 字段
附件 URL 字段上传到 NocoBase 存储引擎后,字段中保存的是稳定 URL。图片缩略图会使用对应的 `preview` 地址。
如果字段保存的是手工输入的外部 URL,并且文件记录没有 `storageId`,NocoBase 会继续保留并返回原始外部 URL。这类文件不经过稳定 URL 的权限检查和重定向流程。
### 普通文件预览
图片、PDF、音频、视频和文本预览会直接使用稳定 URL。浏览器请求会携带 NocoBase 登录 cookie,再按当前角色检查附件表或文件表的 `get/view` 权限。
对于对象存储中的 PDF 等文件,最终预览方式还会受到存储服务 CORS 配置的影响。如果自定义前端通过 `fetch()` 读取重定向后的对象存储地址,也需要确保对象存储允许当前站点跨域访问。
### Office 文件预览
Microsoft Office Online Viewer 由 Microsoft 服务端拉取文件,无法携带用户浏览器中的 NocoBase cookie。因此,用户真正打开 Office 预览时,NocoBase 会先检查该文件的查看权限,再签发一个短期临时 URL。
临时 URL 默认有效 10 分钟,可以通过 `TEMPORARY_FILE_ACCESS_EXPIRES_IN` 配置为 5 到 10 分钟。它只绑定当前文件,过期后无法继续使用。重新打开预览时会重新申请,加载失败时预览器也可能重新申请一次。
:::warning 注意
临时 URL 只用于外部预览服务读取文件。不要把它写回附件字段、Markdown 或业务表,也不要把它当成长期分享链接。
:::
### 公开表单
访客在公开表单中上传文件后,NocoBase 会在当前公开表单会话中记录这些文件。上传者可以继续看到自己刚上传的图片或附件。
这个访问范围只服务于当前公开表单会话,并不是通用的公开文件链接。把地址复制到其他浏览器或当前会话失效后,仍可能无法访问。
## 权限和重定向
访问稳定 URL 时,NocoBase 会按照 URL 中的应用、数据源、文件表和记录 ID 定位文件。其中:
1. 已登录用户使用当前应用的登录 cookie 或认证信息,并检查当前角色的文件查看权限。
2. 公开表单等插件可以对特定文件提供额外的受限授权。
3. 检查通过后,NocoBase 返回 `302`,跳转到本地存储或对象存储生成的实际地址。
因此,稳定 URL 隔离了业务数据和存储实现。切换存储域名、更新对象存储签名或调整缩略图规则时,业务字段中保存的地址通常不需要跟着修改。
## 使用注意
- 稳定不等于公开。复制链接给其他人后,对方仍需要登录并拥有文件查看权限
- 稳定不等于永不失效。删除文件记录、删除文件、变更应用或数据源标识、移动到另一张文件表后,原地址会失效
- 不要持久化 `temporaryAccessToken`。它是短期凭证,也可能进入浏览器历史和访问日志
- 不要缓存 `302 Location` 作为永久地址。对象存储签名可能过期,应该每次从稳定 URL 重新解析
- 不要自行替换 URL 中的 `app``dataSource``collection``id` 或扩展名。路径与文件记录不一致时会被拒绝
- 反向代理需要把 `APP_PUBLIC_PATH` 下的 `/files/` 路径转发到 NocoBase。使用子路径部署时,还应保留根路径 `/files/` 的兼容转发规则。使用 NocoBase CLI 生成的代理配置时会自动包含这些规则
- 页面跨源访问 API 的部署(配置了指向其他源的 `API_BASE_URL`)需要把页面来源加入 `CORS_ORIGIN_WHITELIST`,否则登录 cookie 无法写入,稳定 URL 会因缺少凭证返回 `403`,详见[环境变量](../get-started/installation/env.md#api_base_url)
- 部署多个彼此独立的 NocoBase 服务时,应为每个服务使用不同的 `hostname`,不要只通过端口区分。浏览器 cookie 不按端口隔离,详细说明见[生产环境部署](../get-started/deployment/production.md)
- 同一个 NocoBase 部署环境内的子应用会按应用名区分 cookie,不需要单独配置 `hostname`;不过另一个端口上的独立服务如果包含同名主应用或子应用,仍需要通过不同的 `hostname` 隔离
- 如果通过 `<img>``<iframe>``fetch()` 或第三方客户端访问文件,需要确认它会携带凭证,并能跟随 `302` 重定向
- 真正需要长期对外分享文件时,应使用专门的分享或公开访问方案,不要把稳定 URL 或 Office 临时 URL 当成分享链接
## 相关链接
- [HTTP API](./http-api.md) — 通过 API 上传文件并读取返回的稳定 URL
- [文件预览](./file-preview/index.md) — 查看不同文件类型的预览方式
- [Office 文件预览](./file-preview/ms-office.md) — 配置 Microsoft Office Online Viewer
- [存储引擎](./storage/index.md) — 配置本地存储和对象存储
@@ -8,12 +8,34 @@ keywords: "生产环境部署,生产部署,Docker 部署,静态资源代理,Ngin
在生产环境中部署 NocoBase 时,由于不同系统和环境的构建方式存在差异,安装依赖可能较为繁琐。为获得完整功能体验,我们推荐使用 **Docker** 进行部署。如果系统环境无法使用 Docker,也可以使用 **create-nocobase-app** 进行部署。
:::warning
:::warning 注意
不建议直接在生产环境中使用源码部署。源码依赖较多、体积庞大,且全量编译对 CPU 和内存要求较高。如果确实需要使用源码部署,建议先构建自定义 Docker 镜像,再进行部署。
:::
:::warning 注意
如果要部署多个彼此独立的 NocoBase 服务,请为每个服务使用不同的 `hostname`(比如不同的子域名),不要只通过端口区分服务,如 `https://example.com:13000``https://example.com:14000`
NocoBase 会使用 cookie 维持登录状态和[文件访问权限](../../file-manager/stable-url.md)。浏览器发送 cookie 时不会按端口隔离,同一 `hostname` 下不同端口的服务可能共享同名 cookie,导致登录状态互相覆盖,或出现文件预览、下载鉴权失败等问题。
同一个 NocoBase 部署环境内的子应用不在这个限制范围内。登录 cookie 会按应用名区分,主应用和不同名称的子应用可以共享同一个 `hostname`
不过不能据此忽略独立服务之间的隔离。如果在同一 `hostname` 的另一个端口运行了另一个 NocoBase 服务,并且其中存在同名主应用或子应用,cookie 仍可能冲突。
推荐分别使用 `app1.example.com``app2.example.com`,再通过 Nginx 或 Caddy 反向代理到不同的 NocoBase 服务。
:::
## 前后端分离 / 跨源访问 API
推荐让页面和 API 保持同源:通过同一域名下的反向代理,把 `${APP_PUBLIC_PATH}api/``${APP_PUBLIC_PATH}files/` 转发到 NocoBase 服务,`API_BASE_URL` 留空。
如果页面必须跨源访问 API(配置了指向其他源的 `API_BASE_URL`),需要把页面来源加入 `CORS_ORIGIN_WHITELIST`,否则浏览器会忽略 API 响应中的 `Set-Cookie`,登录 cookie 无法写入,文件稳定 URL 的预览和下载会鉴权失败。
同时注意 cookie 按 `hostname` 存储:页面与 API 域名完全不同时,从页面域名访问 `/files/` 不会携带 API 域名下的登录 cookie,这类部署应改为同源反向代理。详见[环境变量](../installation/env.md#api_base_url)。
## 部署流程
生产环境的部署可参考已有的安装和升级步骤。
@@ -95,6 +95,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` 表示让 Caddy 容器通过 Compose 网络访问 `app` 服务
- `./storage` 需要同时挂载到 `app` 和 `caddy` 容器,方便共享代理配置、静态资源和上传文件
- `caddy` 容器启动前需要等待 `nocobase.caddy` 生成,再通过 `ln -sf` 链接到 `/etc/caddy/Caddyfile`
- 自动生成的配置会把 `APP_PUBLIC_PATH` 下的 `/files/` 和根路径 `/files/` 转发到 NocoBase,用于登录鉴权后的文件预览和下载
- 只需要对外暴露 Caddy 容器端口。测试时可以先用 `13000:80`,生产环境通常直接暴露宿主机的 `80` 和 `443`,而 `app` 服务不需要对宿主机暴露端口
## 如果使用宿主机本地 Caddy
@@ -170,6 +171,8 @@ sudo systemctl reload caddy
如果你的宿主机 Caddy 没有使用 `/etc/caddy/Caddyfile`,需要把链接路径改成你自己的配置路径。通常来说,保持 `nocobase.caddy` 作为主入口文件会更稳妥,不建议手动拆开后再复制内容。
如果你没有使用自动生成的配置,而是自行维护 Caddy,请确认 `/files/*` 及 `APP_PUBLIC_PATH` 下对应的文件路径会转发到 NocoBase,并且这些规则位于 SPA 回退规则之前。完整示例见 [Caddy 反向代理](../../nocobase-cli/production/reverse-proxy/caddy.md)。
## 相关链接
- [Docker 安装(内置 Nginx](./docker.mdx) — 从单容器安装开始
@@ -96,6 +96,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` 表示让 Nginx 容器通过 Compose 网络访问 `app` 服务
- `./storage` 需要同时挂载到 `app` 和 `nginx` 容器,方便共享代理配置、静态资源和上传文件
- `nginx` 容器启动前需要等待 `nocobase.conf` 生成,再通过 `ln -sf` 链接到 `/etc/nginx/conf.d/default.conf`
- 自动生成的配置会把 `APP_PUBLIC_PATH` 下的 `/files/` 和根路径 `/files/` 转发到 NocoBase,用于登录鉴权后的文件预览和下载
- 如果使用外部 Nginx,只需要由 `nginx` 容器处理这个端口映射。测试时可以先用 `13000:80`,生产环境通常直接暴露宿主机的 `80` 和 `443`,而 `app` 服务不需要对宿主机暴露端口
## 如果使用宿主机本地 Nginx
@@ -171,6 +172,8 @@ sudo systemctl reload nginx
如果你的宿主机 Nginx 没有使用 `conf.d` 目录,需要把链接路径改成你自己的配置目录。通常来说,保持 `nocobase.conf` 作为 `http {}` 里的 include 文件会更稳妥,不建议手动拆开后再复制内容。
如果你没有使用自动生成的配置,而是自行维护 Nginx,请确认 `/files/` 及 `APP_PUBLIC_PATH` 下对应的文件路径会转发到 NocoBase,并且这些规则位于 SPA 回退规则之前。完整示例见 [Nginx 反向代理](../../nocobase-cli/production/reverse-proxy/nginx.md)。
## 相关链接
- [Docker 安装(内置 Nginx](./docker.mdx) — 从单容器安装开始
@@ -633,7 +633,7 @@ app-postgres-app-1 | 🚀 NocoBase server running at: http://localhost:13000/
下面这份配置把域名请求代理到 `http://127.0.0.1:13000/`
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # 把 your_domain.com 替换成你的域名
@@ -664,6 +664,8 @@ server {
如果你还要启用 HTTPS,可以继续在宿主机 Nginx 上配置 `443` 和证书。NocoBase 容器本身不需要额外处理证书。
这份根路径配置中的 `location /` 会同时代理 `/api/`、`/ws` 和 `/files/`。如果你拆分了静态资源和应用路由,仍需要确保 `/files/` 被转发到 NocoBase,不能把它当作静态目录处理。
### 子路径部署
如果你要把应用部署到子路径,比如 `https://your_domain.com/nocobase/`,那么需要先配置 `APP_PUBLIC_PATH` 环境变量:
@@ -680,7 +682,7 @@ services:
接着把宿主机 Nginx 配置成同样的子路径代理:
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # 把 your_domain.com 替换成你的域名
@@ -706,10 +708,32 @@ server {
send_timeout 600;
proxy_buffering off;
}
# 兼容根路径形式的文件访问 URL。
location ^~ /files/ {
proxy_pass http://127.0.0.1:13000;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $upstream_x_forwarded_proto;
proxy_set_header Host $final_host;
proxy_set_header Referer $http_referer;
proxy_set_header User-Agent $http_user_agent;
add_header Cache-Control "no-cache, no-store" always;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
}
}
```
关键点只有一个——`APP_PUBLIC_PATH` 和 `proxy_pass` 里的路径必须保持一致。只要其中一边少了 `/nocobase/`,静态资源和路由通常就会不正常。
其中:
- `APP_PUBLIC_PATH` 和 `proxy_pass` 里的路径必须保持一致。只要其中一边少了 `/nocobase/`,静态资源和路由通常就会不正常
- `/nocobase/files/` 会由 `location /nocobase/` 转发;根路径的 `/files/` 兼容入口需要单独转发到 NocoBase
### 其他方案
@@ -92,6 +92,39 @@ API_BASE_PATH=/api/
### API_BASE_URL
前端页面访问 NocoBase API 使用的基础地址,默认为空,表示使用与页面同源的 `${APP_PUBLIC_PATH}api/`
```bash
API_BASE_URL=
```
只有当页面和 API 服务不同源(协议、域名、端口任一不同)时,才需要配置为 API 的完整地址:
```bash
API_BASE_URL=https://api.example.com/api/
```
:::warning{title="跨源部署注意"}
NocoBase 使用 cookie 维持登录状态和[文件稳定 URL](../../file-manager/stable-url.md)的访问权限。当 `API_BASE_URL` 与页面不同源时:
- 必须把页面来源加入 [`CORS_ORIGIN_WHITELIST`](#cors_origin_whitelist),否则浏览器会忽略 API 响应中的 `Set-Cookie`,登录 cookie 无法写入,文件预览、下载等依赖 cookie 的功能会鉴权失败(403)。
- cookie 按 `hostname` 存储。如果页面和 API 使用完全不同的域名,浏览器从页面域名访问 `/files/` 稳定 URL 时不会携带 API 域名下的登录 cookie,文件访问仍会失败。
因此推荐优先通过反向代理让页面与 API 保持同源,并将 `API_BASE_URL` 留空。
:::
### CORS_ORIGIN_WHITELIST
允许跨源携带凭证(cookie)访问 API 的来源白名单,多个来源以逗号分隔,默认为空。
```bash
CORS_ORIGIN_WHITELIST=https://www.example.com,https://admin.example.com
```
- 未配置时,只有与 API 同源的请求会被视为可信来源;跨源请求仍可匿名调用 API,但浏览器不允许其读写 cookie。
- 配置后,白名单中的来源会获得精确回显的 `Access-Control-Allow-Origin``Access-Control-Allow-Credentials: true` 响应头,浏览器才会在跨源请求中发送并保存登录 cookie。
- 登录接口会校验请求的 `Origin` / `Referer` 是否可信,来自白名单之外的跨源登录请求会被拒绝(403)。
### CLUSTER_MODE
> `v1.6.0+`
@@ -68,6 +68,16 @@ nb app autostart run
- 如果准备接反向代理,env 里已经保存了 `appPort`
- 如果准备正式对外开放,已经规划好域名、入口端口和 HTTPS 方案
:::warning 注意
如果要部署多个彼此独立的 NocoBase 服务,请为每个服务使用不同的 `hostname`(比如不同的子域名),不要只通过端口区分服务。浏览器 cookie 不按端口隔离,同一 `hostname` 下的不同服务可能互相覆盖登录状态,并影响[稳定 URL](../../file-manager/stable-url.md)的文件访问鉴权。
同一个 NocoBase 部署环境内的子应用会按应用名区分 cookie,不需要为每个子应用配置独立的 `hostname`。不过,如果同一 `hostname` 的另一个端口运行了另一个 NocoBase 服务,并且其中存在同名主应用或子应用,cookie 仍可能冲突。
比如,推荐使用 `app1.example.com``app2.example.com`,不要使用 `example.com:13000``example.com:14000`
:::
如果你还没有完成 CLI 安装或 env 初始化,先回到 [使用 CLI 安装应用](../installation/cli.md)。
如果命令提示 env 缺少 `appPort`,先执行 [`nb env update`](../../api/cli/env/update.md) 补上。
@@ -124,7 +124,7 @@ nb proxy caddy reload
如果你的应用不是 CLI 托管的,或者你明确要自己维护完整的 Caddy 配置,也可以手写。
不过对于 NocoBase 来说,生产环境入口通常不只是一个简单的 `reverse_proxy`。除了把 API 请求转发到后端应用之外,一份完整可用的 Caddy 配置通常还需要同时处理上传目录、前端静态资源、`.well-known` 路由、WebSocket,以及 SPA 回退页。
不过对于 NocoBase 来说,生产环境入口通常不只是一个简单的 `reverse_proxy`。除了把 API 请求转发到后端应用之外,一份完整可用的 Caddy 配置通常还需要同时处理上传目录、前端静态资源、文件访问入口 `/files/``.well-known` 路由、WebSocket,以及 SPA 回退页。
`test2` 为例,和 Caddy 相关的关键目录通常包括:
@@ -139,6 +139,7 @@ nb proxy caddy reload
- `dist`:暴露前端构建产物目录
- `oauth well-known`:处理 OAuth 发现路径
- `openid well-known`:处理 OpenID 发现路径
- `files`:把 `/files/` 下的文件访问请求转发到后端应用
- `api`:转发 `/api/` 请求到后端应用
- `ws`:转发 WebSocket 请求到后端应用
- `spa v2`:为 `/v/` 提供前端入口及回退页
@@ -187,6 +188,10 @@ c.local.nocobase.com {
reverse_proxy host.docker.internal:56575
}
handle /files/* {
reverse_proxy host.docker.internal:56575
}
handle /api/* {
reverse_proxy host.docker.internal:56575
}
@@ -249,7 +254,15 @@ NB_CLI_ROOT/test2/storage/uploads
2. 以生成结果作为基准确认路由结构和实际路径
3. 再根据你的域名、运行方式和挂载路径做手工调整
这样通常比从零手写一份配置更不容易漏掉 WebSocket、静态资源、上传目录、`.well-known` 路由或 SPA 回退页相关的细节。
这样通常比从零手写一份配置更不容易漏掉 `/files/`WebSocket、静态资源、上传目录、`.well-known` 路由或 SPA 回退页相关的细节。
:::warning 注意
`/files/` 是需要经过 NocoBase 鉴权的应用路由,不能作为静态目录处理,也不能落入 SPA 回退页。手写配置时,需要把它转发到 NocoBase 后端,并放在 `handle_path /*` 等前端回退规则之前。
如果配置了 `APP_PUBLIC_PATH=/nocobase/`,还需要转发 `/nocobase/files/*`。为了兼容已有的根路径文件地址,建议同时保留 `/files/*` 转发规则。
:::
## 检查并重载配置
@@ -8,7 +8,7 @@ keywords: "NocoBase,nb proxy nginx,nb proxy caddy,反向代理,Nginx,Caddy,生
这篇只适用于使用 `nb init` 安装的应用。
在 NocoBase 里,生产环境反向代理不只是简单把请求转发到应用进程。通常还要同时处理 WebSocket、子路径、前端静态资源、上传目录和 SPA 回退页这些细节。
在 NocoBase 里,生产环境反向代理不只是简单把请求转发到应用进程。通常还要同时处理 WebSocket、子路径、前端静态资源、上传目录、文件访问入口 `/files/` 和 SPA 回退页这些细节。
`nb proxy` 的作用,就是把这些容易漏掉的细节统一收进一组稳定的命令入口里。
@@ -122,7 +122,7 @@ nb proxy nginx reload
如果你的应用不是 CLI 托管的,或者你明确要自己维护完整的 Nginx 配置,也可以手写。
不过对于 NocoBase 来说,生产环境反向代理通常不只是一个简单的 `proxy_pass`。除了把 API 请求转发到后端应用之外,一份完整可用的配置通常还需要同时处理上传目录、前端静态资源、WebSocket、`.well-known` 路由,以及 SPA 回退页。
不过对于 NocoBase 来说,生产环境反向代理通常不只是一个简单的 `proxy_pass`。除了把 API 请求转发到后端应用之外,一份完整可用的配置通常还需要同时处理上传目录、前端静态资源、文件访问入口 `/files/`WebSocket、`.well-known` 路由,以及 SPA 回退页。
`test2` 为例,和 Nginx 相关的关键文件与目录通常包括:
@@ -138,6 +138,7 @@ nb proxy nginx reload
- `uploads`:通过 `alias` 暴露上传目录
- `dist`:通过 `alias` 暴露前端构建产物目录
- `well-known`:处理 OAuth / OpenID 相关发现路径
- `files`:把 `/files/` 下的文件访问请求转发到后端应用
- `api`:转发 `/api/` 请求到后端应用
- `ws`:转发 WebSocket 请求到后端应用
- `spa`:为 `/``/v/` 提供前端入口及 `try_files` 回退
@@ -180,6 +181,11 @@ server {
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /files/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /api/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
@@ -229,7 +235,15 @@ nb proxy nginx generate --env test2 --host c.local.nocobase.com
2. 以生成结果作为基准确认路由结构和实际路径
3. 再根据你的域名、运行方式和挂载路径做手工调整
这样通常比从零手写一份配置更不容易漏掉 WebSocket、静态资源、上传目录或 SPA 回退页相关的细节。
这样通常比从零手写一份配置更不容易漏掉 `/files/`WebSocket、静态资源、上传目录或 SPA 回退页相关的细节。
:::warning 注意
`/files/` 是需要经过 NocoBase 鉴权的应用路由,不能作为静态目录处理,也不能落入 SPA 回退页。手写配置时,需要把它转发到 NocoBase 后端,并放在 `location /` 等前端回退规则之前。
如果配置了 `APP_PUBLIC_PATH=/nocobase/`,还需要转发 `/nocobase/files/`。为了兼容已有的根路径文件地址,建议同时保留 `/files/` 转发规则。
:::
## HTTPS 怎么处理
+5
View File
@@ -59,6 +59,11 @@
"label": "Anhangsfeld",
"link": "/file-manager/field-attachment"
},
{
"type": "custom-link",
"label": "Stabile URL",
"link": "/file-manager/stable-url"
},
{
"type": "custom-link",
"label": "Dateivorschau",
+57
View File
@@ -0,0 +1,57 @@
---
pkg: '@nocobase/plugin-file-manager'
title: "Stabile URL (Proxy-URL)"
description: "Beschreibt Format, Berechtigungen, Weiterleitungen und das Verhalten stabiler Datei-URLs in NocoBase."
keywords: "stabile URL,Proxy-URL,permanente URL,Dateizugriff,Office-Vorschau,NocoBase"
---
# Stabile URL
Dateien, die von einer NocoBase-Speicher-Engine verwaltet werden, sind über eine **stabile URL** erreichbar. NocoBase prüft zuerst den Dateidatensatz und die Berechtigungen und leitet anschließend zur tatsächlichen Speicher-URL weiter.
## Format
```text
/files/<app>/<dataSource>/<collection>/<id><extname>
```
Bei `APP_PUBLIC_PATH=/nocobase` beginnt der Pfad mit `/nocobase/files/`. ID und Erweiterung können nach dem Erstellen nicht geändert werden. Daher bleibt die URL stabil, solange der Datensatz existiert.
| Zweck | URL | Verhalten |
|---|---|---|
| Öffnen | `/files/.../42.pdf` | Prüft die Berechtigung und leitet zur Datei weiter |
| Vorschau | `/files/.../42.png?preview=1` | Leitet zur Vorschau oder Miniaturansicht weiter |
| Download | `/files/.../42.pdf?download=1` | Leitet mit Download-Semantik weiter |
| Office | `/files/.../42.xlsx?temporaryAccessToken=...` | Kurzzeitiger Zugriff für Office Online Viewer |
## Verhalten in NocoBase
- Anhangsfelder, Dateitabellen und die [HTTP API](./http-api.md) geben stabile URLs in `url` und `preview` zurück
- Markdown speichert die stabile URL und unterstützt private S3-, OSS-, COS- und S3-Pro-Speicher
- Das Anhang-URL-Feld behält manuell eingegebene externe URLs bei und verwendet für verwaltete Uploads die stabile URL
- Normale Vorschauen verwenden die aktuelle NocoBase-Sitzung und die Dateiberechtigungen
- Öffentliche Formulare gewähren nur begrenzten Zugriff auf Dateien, die in der aktuellen Formularsitzung hochgeladen wurden
## Office-Vorschau
Microsoft Office Online Viewer kann das NocoBase-Cookie des Benutzers nicht verwenden. Beim Öffnen prüft NocoBase zuerst die Berechtigung und stellt dann eine temporäre, an die Datei gebundene URL aus. Sie gilt standardmäßig 10 Minuten und kann mit `TEMPORARY_FILE_ACCESS_EXPIRES_IN` auf 5 bis 10 Minuten eingestellt werden.
Speichere diese URL nicht in Feldern, Markdown oder Geschäftsdaten und verwende sie nicht als Freigabelink.
## Hinweise
- Stabil bedeutet nicht öffentlich; der Empfänger benötigt weiterhin eine Berechtigung
- Löschen oder Verschieben des Datensatzes macht die alte URL ungültig
- Die Antwort ist eine `302`-Weiterleitung, der Clients folgen müssen
- `302 Location` und `temporaryAccessToken` dürfen nicht dauerhaft gespeichert werden
- Der Reverse Proxy muss `/files/` unter `APP_PUBLIC_PATH` an NocoBase weiterleiten. Bei einer Bereitstellung unter einem Unterpfad sollte zusätzlich die kompatible Route `/files/` auf Root-Ebene erhalten bleiben. Von der NocoBase CLI erzeugte Konfigurationen enthalten beide Regeln automatisch
- Bei Bereitstellungen, bei denen Seiten die API ursprungsübergreifend aufrufen (`API_BASE_URL` zeigt auf einen anderen Origin), muss der Seiten-Ursprung zu `CORS_ORIGIN_WHITELIST` hinzugefügt werden. Andernfalls wird das Anmelde-Cookie nie gespeichert und stabile URLs liefern wegen fehlender Anmeldeinformationen `403`. Siehe [Umgebungsvariablen](../get-started/installation/env.md#api_base_url)
- Verwende für jeden unabhängigen NocoBase-Dienst einen eigenen `hostname`, statt die Dienste nur durch Ports zu unterscheiden. Browser-Cookies werden nicht nach Port getrennt; weitere Informationen findest du unter [Bereitstellung in einer Produktionsumgebung](../get-started/deployment/production.md)
- Unteranwendungen innerhalb derselben NocoBase-Bereitstellung werden anhand des Anwendungsnamens unterschieden und benötigen keine eigenen Hostnames. Ein unabhängiger Dienst auf einem anderen Port muss jedoch weiterhin über einen eigenen Hostname isoliert werden, wenn er eine Haupt- oder Unteranwendung mit demselben Namen enthält
## Verwandte Links
- [HTTP API](./http-api.md) — Dateien hochladen und abfragen
- [Dateivorschau](./file-preview/index.md) — Unterstützte Vorschauformate
- [Office-Dateivorschau](./file-preview/ms-office.md) — Office Viewer konfigurieren
- [Speicher-Engines](./storage/index.md) — Speicher konfigurieren
@@ -2,12 +2,34 @@
Wenn Sie NocoBase in einer Produktionsumgebung bereitstellen, kann die Installation von Abhängigkeiten aufwendig sein, da die Build-Methoden in verschiedenen Systemen und Umgebungen variieren. Für ein vollständiges Funktionserlebnis empfehlen wir die Bereitstellung mit **Docker**. Wenn Ihre Systemumgebung Docker nicht verwenden kann, können Sie auch **create-nocobase-app** für die Bereitstellung nutzen.
:::warning
:::warning Hinweis
Es wird nicht empfohlen, NocoBase direkt aus dem Quellcode in einer Produktionsumgebung bereitzustellen. Der Quellcode hat viele Abhängigkeiten, ist umfangreich und eine vollständige Kompilierung stellt hohe Anforderungen an CPU und Arbeitsspeicher. Wenn Sie unbedingt aus dem Quellcode bereitstellen müssen, wird empfohlen, zuerst ein benutzerdefiniertes Docker-Image zu erstellen und es dann bereitzustellen.
:::
:::warning Hinweis
Wenn Sie mehrere voneinander unabhängige NocoBase-Dienste bereitstellen, verwenden Sie für jeden Dienst einen eigenen `hostname`, etwa unterschiedliche Subdomains. Unterscheiden Sie die Dienste nicht nur über Ports wie `https://example.com:13000` und `https://example.com:14000`.
NocoBase verwendet Cookies für den Anmeldestatus und die [Dateizugriffsrechte](../../file-manager/stable-url.md). Browser trennen Cookies nicht nach Port. Dienste auf verschiedenen Ports unter demselben `hostname` können daher gleichnamige Cookies gemeinsam verwenden, wodurch Anmeldestatus überschrieben oder die Autorisierung von Dateivorschau und Download beeinträchtigt werden kann.
Unteranwendungen innerhalb derselben NocoBase-Bereitstellung fallen nicht unter diese Einschränkung. Anmelde-Cookies werden anhand des Anwendungsnamens unterschieden, sodass die Hauptanwendung und unterschiedlich benannte Unteranwendungen denselben `hostname` verwenden können.
Unabhängige Dienste müssen dennoch isoliert werden. Wenn ein weiterer NocoBase-Dienst auf einem anderen Port unter demselben `hostname` läuft und eine gleichnamige Haupt- oder Unteranwendung enthält, können die Cookies weiterhin kollidieren.
Verwenden Sie beispielsweise `app1.example.com` und `app2.example.com` und leiten Sie diese über Nginx oder Caddy an die jeweiligen NocoBase-Dienste weiter.
:::
## Getrenntes Frontend / Ursprungsübergreifender API-Zugriff
Es ist empfehlenswert, Seiten und API auf demselben Origin zu halten: Verwenden Sie einen Reverse-Proxy unter derselben Domain, der `${APP_PUBLIC_PATH}api/` und `${APP_PUBLIC_PATH}files/` an den NocoBase-Dienst weiterleitet, und lassen Sie `API_BASE_URL` leer.
Wenn die Seiten die API ursprungsübergreifend aufrufen müssen (`API_BASE_URL` zeigt auf einen anderen Origin), fügen Sie den Ursprung der Seiten zu `CORS_ORIGIN_WHITELIST` hinzu. Andernfalls ignoriert der Browser `Set-Cookie` in API-Antworten, das Anmelde-Cookie wird nicht gespeichert und Vorschau sowie Download über stabile Datei-URLs schlagen bei der Autorisierung fehl.
Beachten Sie außerdem, dass Cookies pro `hostname` gespeichert werden: Wenn Seiten und API vollständig unterschiedliche Domains verwenden, enthalten Aufrufe von `/files/` über die Seitendomain nicht das Anmelde-Cookie, das unter der API-Domain gespeichert wurde. Solche Bereitstellungen sollten auf einen Same-Origin-Reverse-Proxy umgestellt werden. Siehe [Umgebungsvariablen](../installation/env.md#api_base_url).
## Bereitstellungsprozess
Für die Bereitstellung in der Produktionsumgebung können Sie sich an den vorhandenen Installations- und Upgrade-Schritten orientieren.
@@ -39,4 +61,4 @@ In einer Produktionsumgebung wird empfohlen, statische Ressourcen von einem Prox
Je nach Installationsmethode können Sie die folgenden Befehle verwenden, um den NocoBase-Prozess zu verwalten:
- [docker compose](./common-commands/docker-compose.md)
- [pm2](./common-commands/pm2.md)
- [pm2](./common-commands/pm2.md)
@@ -94,6 +94,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` ermöglicht dem Caddy-Container den Zugriff auf den Dienst `app` über das Compose-Netzwerk
- `./storage` muss sowohl in `app` als auch in `caddy` gemountet werden, damit Proxy-Konfiguration, statische Dateien und Uploads gemeinsam genutzt werden können
- Der `caddy`-Container sollte warten, bis `nocobase.caddy` erzeugt wurde, und die Datei dann mit `ln -sf` nach `/etc/caddy/Caddyfile` verlinken
- Die erzeugte Konfiguration leitet sowohl die `/files/`-Route unter `APP_PUBLIC_PATH` als auch die Root-Route `/files/` an NocoBase weiter, damit Dateivorschau und Downloads authentifiziert werden können
- Nach außen sollte nur der Port des Caddy-Containers freigegeben werden. Für Tests kannst du mit `13000:80` beginnen; in Produktion werden normalerweise die Host-Ports `80` und `443` direkt veröffentlicht, während der Dienst `app` keinen Port zum Host veröffentlichen muss
## Wenn du ein lokales Caddy auf dem Host verwendest
@@ -169,6 +170,8 @@ sudo systemctl reload caddy
Wenn dein Host-Caddy nicht `/etc/caddy/Caddyfile` verwendet, ersetze das Link-Ziel durch deinen eigenen Konfigurationspfad. In der Regel ist es sicherer, `nocobase.caddy` als Haupteinstiegsdatei zu behalten, statt ihren Inhalt manuell zu kopieren.
Wenn du Caddy selbst verwaltest und nicht die erzeugte Konfiguration verwendest, stelle sicher, dass `/files/*` und die entsprechende Route unter `APP_PUBLIC_PATH` vor den SPA-Fallback-Regeln an NocoBase weitergeleitet werden. Ein vollständiges Beispiel findest du unter [Caddy-Reverse-Proxy](../../nocobase-cli/production/reverse-proxy/caddy.md).
## Verwandte Links
- [Docker-Installation (integriertes Nginx)](./docker.mdx) — Starte mit dem Single-Container-Setup
@@ -95,6 +95,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` ermöglicht dem Nginx-Container den Zugriff auf den Dienst `app` über das Compose-Netzwerk
- `./storage` muss sowohl in `app` als auch in `nginx` gemountet werden, damit Proxy-Konfiguration, statische Dateien und Uploads gemeinsam genutzt werden können
- Der `nginx`-Container sollte warten, bis `nocobase.conf` erzeugt wurde, und die Datei dann mit `ln -sf` nach `/etc/nginx/conf.d/default.conf` verlinken
- Die erzeugte Konfiguration leitet sowohl die `/files/`-Route unter `APP_PUBLIC_PATH` als auch die Root-Route `/files/` an NocoBase weiter, damit Dateivorschau und Downloads authentifiziert werden können
- Wenn du einen externen Nginx-Container verwendest, sollte der `nginx`-Container das Host-Port-Mapping übernehmen. Für Tests kannst du mit `13000:80` beginnen; in Produktion werden normalerweise die Host-Ports `80` und `443` direkt veröffentlicht, während der Dienst `app` keinen Port zum Host veröffentlichen muss
## Wenn du ein lokales Nginx auf dem Host verwendest
@@ -170,6 +171,8 @@ sudo systemctl reload nginx
Wenn dein Host-Nginx kein `conf.d`-Verzeichnis verwendet, ersetze das Link-Ziel durch deinen eigenen Konfigurationspfad. In der Regel ist es sicherer, `nocobase.conf` als Datei zu behalten, die aus dem `http {}`-Kontext eingebunden wird, statt ihren Inhalt manuell zu kopieren.
Wenn du Nginx selbst verwaltest und nicht die erzeugte Konfiguration verwendest, stelle sicher, dass `/files/` und die entsprechende Route unter `APP_PUBLIC_PATH` vor den SPA-Fallback-Regeln an NocoBase weitergeleitet werden. Ein vollständiges Beispiel findest du unter [Nginx-Reverse-Proxy](../../nocobase-cli/production/reverse-proxy/nginx.md).
## Verwandte Links
- [Docker-Installation (integriertes Nginx)](./docker.mdx) — Starte mit dem Single-Container-Setup
@@ -629,7 +629,7 @@ Wenn du das Image mit integriertem Nginx verwendest, ist es normalerweise besser
Die folgende Konfiguration leitet Anfragen an die Domain an `http://127.0.0.1:13000/` weiter:
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # Ersetze your_domain.com durch deine Domain
@@ -660,6 +660,8 @@ server {
Wenn du auch HTTPS aktivieren möchtest, konfiguriere `443` und das Zertifikat im Nginx auf dem Host. Der NocoBase-Container muss Zertifikate nicht separat verarbeiten.
Der Block `location /` in dieser Root-Pfad-Konfiguration leitet auch `/api/`, `/ws` und `/files/` weiter. Wenn du statische Ressourcen und Anwendungsrouten trennst, stelle weiterhin sicher, dass `/files/` an NocoBase weitergeleitet und nicht als statisches Verzeichnis behandelt wird.
### Bereitstellung unter einem Unterpfad
Wenn du die Anwendung unter einem Unterpfad bereitstellen möchtest, etwa `https://your_domain.com/nocobase/`, konfiguriere zuerst die Umgebungsvariable `APP_PUBLIC_PATH`:
@@ -676,7 +678,7 @@ Behalte den führenden und abschließenden `/` im Pfad bei. Nach der Konfigurati
Konfiguriere anschließend Nginx auf dem Host mit demselben Unterpfad:
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # Ersetze your_domain.com durch deine Domain
@@ -702,10 +704,32 @@ server {
send_timeout 600;
proxy_buffering off;
}
# Kompatibilität mit Dateizugriffs-URLs auf Root-Ebene beibehalten.
location ^~ /files/ {
proxy_pass http://127.0.0.1:13000;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $upstream_x_forwarded_proto;
proxy_set_header Host $final_host;
proxy_set_header Referer $http_referer;
proxy_set_header User-Agent $http_user_agent;
add_header Cache-Control "no-cache, no-store" always;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
}
}
```
Wichtig ist, dass `APP_PUBLIC_PATH` und der Pfad in `proxy_pass` übereinstimmen. Wenn auf einer Seite `/nocobase/` fehlt, funktionieren statische Dateien und Routing normalerweise nicht korrekt.
Beachte dabei:
- `APP_PUBLIC_PATH` und der Pfad in `proxy_pass` müssen übereinstimmen. Wenn auf einer Seite `/nocobase/` fehlt, funktionieren statische Dateien und Routing normalerweise nicht korrekt
- `/nocobase/files/` wird durch `location /nocobase/` weitergeleitet; die kompatible Root-Route `/files/` muss separat an NocoBase weitergeleitet werden
### Weitere Optionen
@@ -86,6 +86,39 @@ API_BASE_PATH=/api/
### API_BASE_URL
Die Basis-URL, die das Frontend für den Zugriff auf die NocoBase-API verwendet. Standardmäßig leer, was bedeutet, dass `${APP_PUBLIC_PATH}api/` derselben Origin verwendet wird.
```bash
API_BASE_URL=
```
Setzen Sie diesen Wert nur auf die vollständige API-Adresse, wenn Seiten und API-Dienst unterschiedliche Origins haben (abweichendes Protokoll, Domain oder Port):
```bash
API_BASE_URL=https://api.example.com/api/
```
:::warning{title="Hinweise zu ursprungsübergreifenden Bereitstellungen"}
NocoBase verwendet Cookies, um den Anmeldestatus und den Zugriff auf [stabile Datei-URLs](../../file-manager/stable-url.md) zu autorisieren. Wenn `API_BASE_URL` auf eine andere Origin als die Seiten zeigt:
- Der Ursprung der Seiten muss zu [`CORS_ORIGIN_WHITELIST`](#cors_origin_whitelist) hinzugefügt werden. Andernfalls ignoriert der Browser `Set-Cookie` in API-Antworten, das Anmelde-Cookie wird nicht gespeichert und Cookie-abhängige Funktionen wie Dateivorschau und Download schlagen mit `403` fehl.
- Cookies werden pro `hostname` gespeichert. Wenn Seiten und API vollständig unterschiedliche Domains verwenden, senden Aufrufe stabiler `/files/`-URLs über die Seitendomain nicht das Anmelde-Cookie mit, das unter der API-Domain gespeichert wurde. Dadurch schlägt der Dateizugriff weiterhin fehl.
Es ist empfehlenswert, Seiten und API per Reverse-Proxy unter derselben Origin bereitzustellen und `API_BASE_URL` leer zu lassen.
:::
### CORS_ORIGIN_WHITELIST
Whitelist von Origins, die ursprungsübergreifend mit Anmeldeinformationen (Cookies) auf die API zugreifen dürfen. Mehrere Origins werden durch Kommas getrennt. Standardmäßig leer.
```bash
CORS_ORIGIN_WHITELIST=https://www.example.com,https://admin.example.com
```
- Wenn nichts konfiguriert ist, gelten nur Requests derselben Origin als vertrauenswürdig. Ursprungsübergreifende Requests können die API weiterhin anonym aufrufen, der Browser darf dafür jedoch keine Cookies lesen oder schreiben.
- Wenn konfiguriert, erhalten Origins in der Whitelist einen exakt zurückgegebenen `Access-Control-Allow-Origin`-Header sowie `Access-Control-Allow-Credentials: true`, sodass der Browser bei ursprungsübergreifenden Requests Anmelde-Cookies senden und speichern kann.
- Die Anmelde-API prüft `Origin` und `Referer` der Anfrage. Ursprungsübergreifende Anmelde-Requests von Origins außerhalb der Whitelist werden mit `403` abgelehnt.
### CLUSTER_MODE
> `v1.6.0+`
@@ -69,6 +69,16 @@ Wenn Sie bei der Frage „Warum brauchen Sie `nb app autostart`“ nicht weiterk
Wenn Sie eine Verbindung zum Reverse-Proxy herstellen möchten, wurde `appPort` in env gespeichert
- Wenn Sie bereit sind, es offiziell für die Außenwelt zu öffnen, haben Sie bereits den Domainnamen, den Eingangsport und die HTTPS-Lösung geplant.
:::warning Hinweis
Verwenden Sie für jeden unabhängigen NocoBase-Dienst einen eigenen `hostname`, etwa eine separate Subdomain, und unterscheiden Sie die Dienste nicht nur über Ports. Browser-Cookies werden nicht nach Port getrennt. Dienste unter demselben `hostname` können daher den Anmeldestatus überschreiben und die Autorisierung von [stabilen URLs](../../file-manager/stable-url.md) beeinträchtigen.
Unteranwendungen innerhalb derselben NocoBase-Bereitstellung werden anhand des Anwendungsnamens unterschieden und benötigen keine eigenen Hostnames. Läuft jedoch ein weiterer unabhängiger NocoBase-Dienst auf einem anderen Port unter demselben `hostname` und enthält er eine gleichnamige Haupt- oder Unteranwendung, können die Cookies weiterhin kollidieren.
Verwenden Sie beispielsweise `app1.example.com` und `app2.example.com` anstelle von `example.com:13000` und `example.com:14000`.
:::
Wenn Sie die CLI-Installation oder Env-Initialisierung noch nicht abgeschlossen haben, kehren Sie zu [Installation mit CLI (empfohlen)](../installation/cli.md) zurück.
Wenn der Befehl anzeigt, dass in der Umgebung `appPort` fehlt, führen Sie zunächst [`nb env update`](../../api/cli/env/update.md) aus, um es auszufüllen.
@@ -124,7 +124,7 @@ Wenn Sie die Caddy-Konfiguration auf Site-Ebene ausgleichen möchten, z. B. zus
Wenn Ihre Anwendung nicht CLI-gehostet ist oder Sie die komplette Caddy-Konfiguration ausdrücklich selbst pflegen möchten, können Sie diese auch manuell schreiben.
Für NocoBase ist der Produktionsumgebungseintrag jedoch normalerweise nicht nur ein einfacher `reverse_proxy`. Neben der Weiterleitung von API-Anfragen an die Backend-Anwendung muss eine vollständige und funktionierende Caddy-Konfiguration in der Regel auch das Upload-Verzeichnis, statische Front-End-Ressourcen, `.well-known`-Routing, WebSocket und SPA-Fallback-Seite verwalten.
Für NocoBase ist der Produktionsumgebungseintrag jedoch normalerweise nicht nur ein einfacher `reverse_proxy`. Neben der Weiterleitung von API-Anfragen an die Backend-Anwendung muss eine vollständige und funktionierende Caddy-Konfiguration in der Regel auch das Upload-Verzeichnis, statische Front-End-Ressourcen, die Dateizugriffsroute `/files/`, `.well-known`-Routing, WebSocket und SPA-Fallback-Seiten verwalten.
Am Beispiel von `test2` umfassen die wichtigsten Verzeichnisse im Zusammenhang mit Caddy normalerweise:
@@ -139,6 +139,7 @@ Mit anderen Worten: Die handschriftliche Konfiguration muss in der Regel mindest
- `dist`: Stellen Sie das Front-End-Build-Produktverzeichnis bereit
- `oauth well-known`: Behandelt OAuth-Erkennungspfade
- `openid well-known`: Behandelt OpenID-Erkennungspfade
- `files`: Leitet Dateizugriffsanfragen unter `/files/` an die Backend-Anwendung weiter
- `api`: `/api/`-Anfrage an die Backend-Anwendung weiterleiten
- `ws`: WebSocket-Anfragen an die Backend-Anwendung weiterleiten
- `spa v2`: Bietet eine Front-End-Eingabe- und Rückgabeseite für `/v/`
@@ -187,6 +188,10 @@ c.local.nocobase.com {
reverse_proxy host.docker.internal:56575
}
handle /files/* {
reverse_proxy host.docker.internal:56575
}
handle /api/* {
reverse_proxy host.docker.internal:56575
}
@@ -249,7 +254,15 @@ Ein umsichtigerer Ansatz ist normalerweise:
2. Bestätigen Sie die Routing-Struktur und den tatsächlichen Pfad basierend auf den generierten Ergebnissen.
3. Nehmen Sie dann manuelle Anpassungen entsprechend Ihrem Domainnamen, Ausführungsmodus und Bereitstellungspfad vor.
Dabei ist es normalerweise weniger wahrscheinlich, dass Details zu WebSockets, statischen Ressourcen, Upload-Verzeichnissen, `.well-known`-Routen oder SPA-Fallback-Seiten übersehen werden, als wenn Sie eine Konfiguration von Grund auf neu schreiben.
Dabei ist es normalerweise weniger wahrscheinlich, dass Details zu `/files/`, WebSockets, statischen Ressourcen, Upload-Verzeichnissen, `.well-known`-Routen oder SPA-Fallback-Seiten übersehen werden, als wenn Sie eine Konfiguration von Grund auf neu schreiben.
:::warning Hinweis
`/files/` ist eine Anwendungsroute, die die NocoBase-Autorisierung durchlaufen muss. Behandeln Sie sie nicht als statisches Verzeichnis und lassen Sie sie nicht in den SPA-Fallback fallen. Leiten Sie die Route an das NocoBase-Backend weiter und platzieren Sie die Regel vor `handle_path /*` und anderen Front-End-Fallback-Regeln.
Wenn `APP_PUBLIC_PATH=/nocobase/` konfiguriert ist, leiten Sie zusätzlich `/nocobase/files/*` weiter. Behalten Sie die Root-Regel `/files/*` zur Kompatibilität mit vorhandenen Datei-URLs bei.
:::
## Konfiguration prüfen und neu laden
@@ -9,7 +9,7 @@ keywords: "NocoBase, NB-Proxy-Nginx, NB-Proxy-Caddy, Reverse-Proxy, Nginx, Caddy
Dieser Artikel gilt nur für Anwendungen, die mit `nb init` installiert wurden.
In NocoBase leistet der Reverse-Proxy der Produktionsumgebung mehr als nur die Weiterleitung von Anfragen an den Anwendungsprozess. Oftmals werden auch die Details von WebSockets, Unterpfaden, statischen Front-End-Ressourcen, Upload-Verzeichnissen und SPA-Fallback-Seiten gleichzeitig behandelt.
In NocoBase leistet der Reverse-Proxy der Produktionsumgebung mehr als nur die Weiterleitung von Anfragen an den Anwendungsprozess. Er muss auch WebSockets, Unterpfade, statische Front-End-Ressourcen, Upload-Verzeichnisse, die Dateizugriffsroute `/files/` und SPA-Fallback-Seiten verarbeiten.
Die Funktion von `nb proxy` besteht darin, diese leicht übersehenen Details in einem stabilen Satz von Befehlseinträgen zusammenzufassen.
@@ -122,7 +122,7 @@ Wenn Sie eine Nginx-Konfiguration auf Site-Ebene hinzufügen möchten, z. B. Str
Wenn Ihre Anwendung nicht über die CLI gehostet wird oder Sie die komplette Nginx-Konfiguration ausdrücklich selbst pflegen möchten, können Sie diese auch manuell schreiben.
Für NocoBase ist der Produktions-Reverse-Proxy jedoch normalerweise mehr als ein einfacher `proxy_pass`. Zusätzlich zur Weiterleitung von API-Anfragen an die Back-End-Anwendung muss eine vollständige und nutzbare Konfiguration normalerweise das Upload-Verzeichnis, die statischen Front-End-Ressourcen, WebSocket, die `.well-known`-Route und die SPA-Fallback-Seite verwalten.
Für NocoBase ist der Produktions-Reverse-Proxy jedoch normalerweise mehr als ein einfacher `proxy_pass`. Zusätzlich zur Weiterleitung von API-Anfragen an die Back-End-Anwendung muss eine vollständige und nutzbare Konfiguration normalerweise das Upload-Verzeichnis, die statischen Front-End-Ressourcen, die Dateizugriffsroute `/files/`, WebSocket, die `.well-known`-Route und SPA-Fallback-Seiten verwalten.
Am Beispiel von `test2` umfassen wichtige Dateien und Verzeichnisse im Zusammenhang mit Nginx normalerweise:
@@ -138,6 +138,7 @@ Mit anderen Worten: Die handschriftliche Konfiguration muss in der Regel mindest
- `uploads`: Stellen Sie das Upload-Verzeichnis über `alias` bereit.
- `dist`: Machen Sie das Front-End-Build-Produktverzeichnis über `alias` verfügbar.
- `well-known`: Behandelt OAuth-/OpenID-bezogene Erkennungspfade
- `files`: Leitet Dateizugriffsanfragen unter `/files/` an die Backend-Anwendung weiter
- `api`: `/api/`-Anfrage an die Backend-Anwendung weiterleiten
- `ws`: WebSocket-Anfragen an die Backend-Anwendung weiterleiten
- `spa`: Bietet Front-End-Eintrag und `try_files` Fallback für `/` und `/v/`
@@ -180,6 +181,11 @@ server {
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /files/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /api/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
@@ -229,7 +235,15 @@ Ein umsichtigerer Ansatz ist normalerweise:
2. Bestätigen Sie die Routing-Struktur und den tatsächlichen Pfad basierend auf den generierten Ergebnissen.
3. Nehmen Sie dann manuelle Anpassungen entsprechend Ihrem Domainnamen, Ausführungsmodus und Bereitstellungspfad vor.
Dabei ist es in der Regel weniger wahrscheinlich, dass Details zu WebSockets, statischen Ressourcen, Upload-Verzeichnissen oder SPA-Fallback-Seiten übersehen werden, als wenn Sie eine Konfiguration von Grund auf neu schreiben.
Dabei ist es in der Regel weniger wahrscheinlich, dass Details zu `/files/`, WebSockets, statischen Ressourcen, Upload-Verzeichnissen oder SPA-Fallback-Seiten übersehen werden, als wenn Sie eine Konfiguration von Grund auf neu schreiben.
:::warning Hinweis
`/files/` ist eine Anwendungsroute, die die NocoBase-Autorisierung durchlaufen muss. Behandeln Sie sie nicht als statisches Verzeichnis und lassen Sie sie nicht in den SPA-Fallback fallen. Leiten Sie die Route an das NocoBase-Backend weiter und platzieren Sie die Regel vor `location /` und anderen Front-End-Fallback-Regeln.
Wenn `APP_PUBLIC_PATH=/nocobase/` konfiguriert ist, leiten Sie zusätzlich `/nocobase/files/` weiter. Behalten Sie die Root-Regel `/files/` zur Kompatibilität mit vorhandenen Datei-URLs bei.
:::
## Wie man mit HTTPS umgeht
+5
View File
@@ -59,6 +59,11 @@
"label": "Attachment Field",
"link": "/file-manager/field-attachment"
},
{
"type": "custom-link",
"label": "Stable URL",
"link": "/file-manager/stable-url"
},
{
"type": "custom-link",
"label": "File Preview",
+87
View File
@@ -0,0 +1,87 @@
---
pkg: '@nocobase/plugin-file-manager'
title: "Stable URL (proxy URL)"
description: "Explains NocoBase stable file URLs, access permissions, redirects, temporary Office preview URLs, and behavior across file-related features."
keywords: "stable URL,proxy URL,permanent URL,file access,file permissions,Office preview,NocoBase"
---
# Stable URL
Files managed by a NocoBase storage engine are accessed through a **stable URL**. The URL first reaches NocoBase, where the file record and access permissions are checked, and then redirects to the actual URL generated by the storage engine.
## URL format
```text
/files/<app>/<dataSource>/<collection>/<id><extname>
```
For example:
```text
/files/main/main/attachments/42.pdf
```
When `APP_PUBLIC_PATH=/nocobase` is configured, the URL starts with `/nocobase/files/`. The path identifies the app, data source, file collection, record ID, and extension. The ID and extension cannot be changed after creation, which keeps the URL stable for the lifetime of the record.
## URL variants
| Purpose | URL | Behavior |
|---|---|---|
| Open or embed | `/files/.../42.pdf` | Checks permission and redirects to the actual file URL |
| Preview | `/files/.../42.png?preview=1` | Redirects to the preview or thumbnail URL |
| Download | `/files/.../42.pdf?download=1` | Redirects with download semantics |
| Office preview | `/files/.../42.xlsx?temporaryAccessToken=...` | Allows Microsoft Office Online Viewer to fetch one file for a short time |
:::tip
Use the `url` and `preview` values returned by NocoBase. Application code normally should not construct `/files` URLs or their query parameters.
:::
## Behavior across NocoBase
- Attachment fields and file collections return stable URLs after upload and when records are queried
- [HTTP API](./http-api.md) responses no longer expose local paths, storage domains, or presigned download URLs
- Markdown uploads store the stable URL, including files in private S3, OSS, COS, or S3 Pro storage
- Attachment URL fields store a stable URL for managed uploads, while manually entered external URLs remain unchanged
- Image, PDF, audio, video, and text previews use the stable URL and the current NocoBase login session
- Public forms grant limited access to files uploaded in the current public-form browser session; this does not create a generally public link
## Office preview
Microsoft Office Online Viewer fetches the file from Microsoft servers and cannot use the user's NocoBase cookie. When the user opens an Office preview, NocoBase first checks the user's file permission and then issues a temporary URL for that file.
The URL is valid for 10 minutes by default. `TEMPORARY_FILE_ACCESS_EXPIRES_IN` may be set from 5 to 10 minutes. It is requested again when the preview is reopened and must never be saved in an attachment field, Markdown content, or a business record.
## Permissions and redirects
Logged-in requests use the current app credentials and role. After permission is granted, NocoBase responds with `302` and redirects to the local or object-storage URL.
Stable URLs support `GET` and `HEAD`. Other methods return `405`. A command-line client must follow redirects, for example:
```bash
curl -L \
-H "Authorization: Bearer <JWT>" \
"https://example.com/files/main/main/attachments/42.pdf"
```
## Important notes
- Stable does not mean public; recipients still need permission to view the file
- Deleting the record or changing its app, data source, or collection context invalidates the old URL
- Do not persist `temporaryAccessToken` or use it as a sharing link
- Do not cache the `302 Location` as a permanent URL because storage signatures can expire
- Do not rewrite the app, data source, collection, ID, or extension in the path
- Reverse proxies must forward the `/files/` route under `APP_PUBLIC_PATH` to NocoBase. For subpath deployments, keep a compatible root-level `/files/` route as well. Configurations generated by the NocoBase CLI include both routes automatically
- Deployments where the pages access the API cross-origin (with `API_BASE_URL` pointing to another origin) must add the page origin to `CORS_ORIGIN_WHITELIST`; otherwise the login cookie is never stored and stable URLs return `403` for lack of credentials. See [Environment Variables](../get-started/installation/env.md#api_base_url)
- Use a different `hostname` for each independent NocoBase service instead of separating services only by port. Browser cookies are not isolated by port; see [Production Environment Deployment](../get-started/deployment/production.md)
- Sub-apps in the same NocoBase deployment are distinguished by app name and do not need separate hostnames. However, an independent service on another port still needs hostname isolation if it contains a main app or sub-app with the same name
- Custom `fetch()` code may also need object-storage CORS after following the redirect
- Use a dedicated sharing or public-access feature when a long-lived public link is required
## Related links
- [HTTP API](./http-api.md) — Upload and query files through the API
- [File preview](./file-preview/index.md) — Preview behavior for supported file types
- [Office file preview](./file-preview/ms-office.md) — Configure Microsoft Office Online Viewer
- [Storage engines](./storage/index.md) — Configure local and object storage
@@ -2,12 +2,34 @@
When deploying NocoBase in a production environment, installing dependencies can be cumbersome due to differences in build methods across various systems and environments. For a complete functional experience, we recommend deploying with **Docker**. If your system environment cannot use Docker, you can also deploy using **create-nocobase-app**.
:::warning
:::warning Note
It is not recommended to deploy directly from source code in a production environment. The source code has many dependencies, is large in size, and a full compilation has high CPU and memory requirements. If you must deploy from source code, it is recommended to first build a custom Docker image and then deploy it.
:::
:::warning Note
If you deploy multiple independent NocoBase services, use a different `hostname` for each service, such as separate subdomains. Do not distinguish services only by port, for example `https://example.com:13000` and `https://example.com:14000`.
NocoBase uses cookies to maintain login state and [file access permissions](../../file-manager/stable-url.md). Browsers do not isolate cookies by port, so services on different ports under the same `hostname` may share cookies with the same name. This can overwrite login state or cause file preview and download authorization failures.
Sub-apps within the same NocoBase deployment are outside this restriction. Login cookies are distinguished by app name, so the main app and differently named sub-apps can share one `hostname`.
However, independent services still need isolation. If another NocoBase service runs on a different port under the same `hostname` and contains a main app or sub-app with the same name, its cookies may still conflict.
Use addresses such as `app1.example.com` and `app2.example.com`, then route them to different NocoBase services through Nginx or Caddy.
:::
## Separated Frontend / Cross-Origin API Access
Prefer keeping the pages and the API on the same origin: use a reverse proxy under one domain to forward `${APP_PUBLIC_PATH}api/` and `${APP_PUBLIC_PATH}files/` to the NocoBase service, and leave `API_BASE_URL` empty.
If the pages must access the API cross-origin (with `API_BASE_URL` pointing to another origin), add the page origin to `CORS_ORIGIN_WHITELIST`. Otherwise the browser ignores `Set-Cookie` in API responses, the login cookie is never stored, and preview and download through stable file URLs fail authorization.
Also note that cookies are stored per `hostname`: when the pages and the API use entirely different domains, requests to `/files/` from the page domain will not carry the login cookie stored under the API domain. Such deployments should switch to a same-origin reverse proxy. See [Environment Variables](../installation/env.md#api_base_url).
## Deployment Process
For production environment deployment, you can refer to the existing installation and upgrade steps.
@@ -39,4 +61,4 @@ In a production environment, it is recommended to manage static assets with a pr
Depending on the installation method, you can use the following commands to manage the NocoBase process:
- [docker compose](./common-commands/docker-compose.md)
- [pm2](./common-commands/pm2.md)
- [pm2](./common-commands/pm2.md)
@@ -94,6 +94,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` lets the Caddy container reach the `app` service through the Compose network
- `./storage` must be mounted into both the `app` and `caddy` containers so they can share proxy config, static assets, and uploaded files
- The `caddy` container should wait until `nocobase.caddy` is generated, then link it to `/etc/caddy/Caddyfile` with `ln -sf`
- The generated config forwards both the `/files/` route under `APP_PUBLIC_PATH` and the root-level `/files/` route to NocoBase for authenticated file previews and downloads
- Expose only the Caddy container port to the host. For testing, you can start with `13000:80`; in production, you usually expose the host `80` and `443` ports directly, while the `app` service does not need to expose its port to the host
## If you use a local host Caddy
@@ -169,6 +170,8 @@ sudo systemctl reload caddy
If your host Caddy does not use `/etc/caddy/Caddyfile`, replace the link target with your own config path. Usually it is safer to keep `nocobase.caddy` as the main entry file instead of copying its content manually.
If you maintain Caddy yourself instead of using the generated config, make sure `/files/*` and the corresponding route under `APP_PUBLIC_PATH` are forwarded to NocoBase before the SPA fallback rules. See [Caddy Reverse Proxy](../../nocobase-cli/production/reverse-proxy/caddy.md) for a complete example.
## Related links
- [Docker Installation (Built-in Nginx)](./docker.mdx) — Start with the single-container setup
@@ -95,6 +95,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` lets the Nginx container reach the `app` service through the Compose network
- `./storage` must be mounted into both the `app` and `nginx` containers so they can share proxy config, static assets, and uploaded files
- The `nginx` container should wait until `nocobase.conf` is generated, then link it to `/etc/nginx/conf.d/default.conf` with `ln -sf`
- The generated config forwards both the `/files/` route under `APP_PUBLIC_PATH` and the root-level `/files/` route to NocoBase for authenticated file previews and downloads
- If you use an external Nginx container, let the `nginx` container handle the host port mapping. For testing, you can start with `13000:80`; in production, you usually expose the host `80` and `443` ports directly, while the `app` service does not need to expose its port to the host
## If you use a local host Nginx
@@ -170,6 +171,8 @@ sudo systemctl reload nginx
If your host Nginx does not use the `conf.d` directory, replace the link target with your own config path. Usually it is safer to keep `nocobase.conf` as a file included from the `http {}` context instead of copying its content manually.
If you maintain Nginx yourself instead of using the generated config, make sure `/files/` and the corresponding route under `APP_PUBLIC_PATH` are forwarded to NocoBase before the SPA fallback rules. See [Nginx Reverse Proxy](../../nocobase-cli/production/reverse-proxy/nginx.md) for a complete example.
## Related links
- [Docker Installation (Built-in Nginx)](./docker.mdx) — Start with the single-container setup
@@ -627,7 +627,7 @@ If you use the built-in Nginx image, it is usually better not to expose `13000`
The following config proxies domain requests to `http://127.0.0.1:13000/`:
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # Replace your_domain.com with your domain
@@ -658,6 +658,8 @@ server {
If you also want to enable HTTPS, configure `443` and the certificate on the host Nginx. The NocoBase container does not need to handle certificates separately.
The `location /` block in this root-path configuration also proxies `/api/`, `/ws`, and `/files/`. If you split static assets from application routes, make sure `/files/` is still forwarded to NocoBase and is not handled as a static directory.
### Subpath deployment
If you want to deploy the app under a subpath, such as `https://your_domain.com/nocobase/`, configure the `APP_PUBLIC_PATH` environment variable first:
@@ -674,7 +676,7 @@ Keep the leading and trailing `/` in the path. After this is configured, the app
Then configure the host Nginx with the same subpath proxy:
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # Replace your_domain.com with your domain
@@ -700,10 +702,32 @@ server {
send_timeout 600;
proxy_buffering off;
}
# Keep compatibility with root-level file access URLs.
location ^~ /files/ {
proxy_pass http://127.0.0.1:13000;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $upstream_x_forwarded_proto;
proxy_set_header Host $final_host;
proxy_set_header Referer $http_referer;
proxy_set_header User-Agent $http_user_agent;
add_header Cache-Control "no-cache, no-store" always;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
}
}
```
The key point is that `APP_PUBLIC_PATH` and the path in `proxy_pass` must stay consistent. If either side misses `/nocobase/`, static assets and routing will usually not work correctly.
Keep these points in mind:
- `APP_PUBLIC_PATH` and the path in `proxy_pass` must stay consistent. If either side misses `/nocobase/`, static assets and routing will usually not work correctly
- `/nocobase/files/` is forwarded by `location /nocobase/`; the compatible root-level `/files/` route must be forwarded to NocoBase separately
### Other options
@@ -86,6 +86,39 @@ API_BASE_PATH=/api/
### API_BASE_URL
Base URL the frontend uses to access the NocoBase API. Empty by default, which means the same-origin `${APP_PUBLIC_PATH}api/` is used.
```bash
API_BASE_URL=
```
Only set it to the full API address when the pages and the API service are on different origins (different protocol, domain, or port):
```bash
API_BASE_URL=https://api.example.com/api/
```
:::warning{title="Cross-origin deployments"}
NocoBase uses cookies to maintain login state and to authorize [stable file URLs](../../file-manager/stable-url.md). When `API_BASE_URL` points to a different origin than the pages:
- The page origin must be added to [`CORS_ORIGIN_WHITELIST`](#cors_origin_whitelist). Otherwise the browser ignores `Set-Cookie` in API responses, the login cookie is never stored, and cookie-dependent features such as file preview and download fail with `403`.
- Cookies are stored per `hostname`. If the pages and the API use entirely different domains, requests to `/files/` stable URLs from the page domain will not carry the login cookie stored under the API domain, so file access still fails.
Prefer serving the pages and the API from the same origin through a reverse proxy and leaving `API_BASE_URL` empty.
:::
### CORS_ORIGIN_WHITELIST
Whitelist of origins allowed to access the API cross-origin with credentials (cookies). Multiple origins are separated by commas. Empty by default.
```bash
CORS_ORIGIN_WHITELIST=https://www.example.com,https://admin.example.com
```
- When not configured, only same-origin requests are treated as trusted; cross-origin requests can still call the API anonymously, but the browser is not allowed to read or write cookies for them.
- When configured, whitelisted origins receive an exact `Access-Control-Allow-Origin` echo and `Access-Control-Allow-Credentials: true`, which lets the browser send and store login cookies on cross-origin requests.
- The sign-in API validates the request `Origin` / `Referer`; cross-origin sign-in requests from origins outside the whitelist are rejected with `403`.
### CLUSTER_MODE
> `v1.6.0+`
@@ -69,6 +69,16 @@ If you happen to be stuck here "Why do you need `nb app autostart`", just contin
- If you are going to connect to the reverse proxy, `appPort` has been saved in env
- If you are ready to officially open it to the outside world, you have already planned the domain name, entrance port and HTTPS solution.
:::warning Note
Use a different `hostname`, such as a separate subdomain, for each independent NocoBase service. Do not distinguish services only by port. Browser cookies are not isolated by port, so services under the same `hostname` may overwrite login state and affect [stable URL](../../file-manager/stable-url.md) authorization.
Sub-apps within the same NocoBase deployment are distinguished by app name and do not need separate hostnames. However, if another independent NocoBase service runs on a different port under the same `hostname` and contains a main app or sub-app with the same name, its cookies may still conflict.
For example, use `app1.example.com` and `app2.example.com` instead of `example.com:13000` and `example.com:14000`.
:::
If you have not completed the CLI installation or env initialization, go back to [Install using CLI](../installation/cli.md).
If the command prompts that env is missing `appPort`, first execute [`nb env update`](../../api/cli/env/update.md) to fill it in.
@@ -124,7 +124,7 @@ If you want to make up for Caddy site-level configuration, such as additional he
If your application is not CLI hosted, or you explicitly want to maintain the complete Caddy configuration yourself, you can also write it by hand.
However, for NocoBase, the production environment entry is usually not just a simple `reverse_proxy`. In addition to forwarding API requests to the backend application, a complete and working Caddy configuration usually also needs to handle the upload directory, front-end static resources, `.well-known` routing, WebSocket, and SPA fallback page.
However, for NocoBase, the production environment entry is usually not just a simple `reverse_proxy`. In addition to forwarding API requests to the backend application, a complete and working Caddy configuration usually also needs to handle the upload directory, front-end static resources, the `/files/` file access route, `.well-known` routing, WebSocket, and SPA fallback pages.
Taking `test2` as an example, key directories related to Caddy usually include:
@@ -139,6 +139,7 @@ In other words, handwritten configuration usually needs to cover at least the fo
- `dist`: Expose the front-end build product directory
- `oauth well-known`: Handle OAuth discovery paths
- `openid well-known`: Handle OpenID discovery paths
- `files`: Forward file access requests under `/files/` to the backend application
- `api`: forward `/api/` request to the backend application
- `ws`: forward WebSocket requests to the backend application
- `spa v2`: Provides front-end entry and return page for `/v/`
@@ -187,6 +188,10 @@ c.local.nocobase.com {
reverse_proxy host.docker.internal:56575
}
handle /files/* {
reverse_proxy host.docker.internal:56575
}
handle /api/* {
reverse_proxy host.docker.internal:56575
}
@@ -249,7 +254,15 @@ A more prudent approach is usually:
2. Confirm the routing structure and actual path based on the generated results.
3. Then make manual adjustments according to your domain name, running mode and mounting path.
This is usually less likely to miss details related to WebSockets, static resources, upload directories, `.well-known` routes, or SPA fallback pages than handwriting a configuration from scratch.
This is usually less likely to miss details related to `/files/`, WebSockets, static resources, upload directories, `.well-known` routes, or SPA fallback pages than handwriting a configuration from scratch.
:::warning Note
`/files/` is an application route that must pass through NocoBase authorization. Do not handle it as a static directory or let it fall through to the SPA fallback. Forward it to the NocoBase backend and place the rule before `handle_path /*` and other front-end fallback rules.
If `APP_PUBLIC_PATH=/nocobase/` is configured, also forward `/nocobase/files/*`. Keep the root-level `/files/*` rule for compatibility with existing file URLs.
:::
## Check and reload configuration
@@ -9,7 +9,7 @@ keywords: "NocoBase,nb proxy nginx,nb proxy caddy, reverse proxy, Nginx, Caddy,
This article only applies to applications installed using `nb init`.
In NocoBase, the production environment reverse proxy does more than simply forward requests to the application process. Often the details of WebSockets, subpaths, front-end static resources, upload directories, and SPA fallback pages are also handled at the same time.
In NocoBase, the production environment reverse proxy does more than simply forward requests to the application process. It also needs to handle WebSockets, subpaths, front-end static resources, upload directories, the `/files/` file access route, and SPA fallback pages.
The function of `nb proxy` is to collect these easily missed details into a stable set of command entries.
@@ -122,7 +122,7 @@ If you want to add site-level Nginx configuration, such as current limiting, add
If your application is not CLI hosted, or you explicitly want to maintain the complete Nginx configuration yourself, you can also write it by hand.
However, for NocoBase, the production reverse proxy is usually more than a simple `proxy_pass`. In addition to forwarding API requests to the backend application, a complete and usable configuration usually needs to handle the upload directory, front-end static resources, WebSocket, `.well-known` route, and SPA fallback page.
However, for NocoBase, the production reverse proxy is usually more than a simple `proxy_pass`. In addition to forwarding API requests to the backend application, a complete and usable configuration usually needs to handle the upload directory, front-end static resources, the `/files/` file access route, WebSocket, the `.well-known` route, and SPA fallback pages.
Taking `test2` as an example, key files and directories related to Nginx usually include:
@@ -138,6 +138,7 @@ In other words, handwritten configuration usually needs to cover at least the fo
- `uploads`: Expose the upload directory through `alias`
- `dist`: Expose the front-end build product directory through `alias`
- `well-known`: Handle OAuth / OpenID related discovery paths
- `files`: Forward file access requests under `/files/` to the backend application
- `api`: forward `/api/` request to the backend application
- `ws`: forward WebSocket requests to the backend application
- `spa`: Provides front-end entry and `try_files` fallback for `/` and `/v/`
@@ -180,6 +181,11 @@ server {
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /files/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /api/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
@@ -229,7 +235,15 @@ A more prudent approach is usually:
2. Confirm the routing structure and actual path based on the generated results.
3. Then make manual adjustments according to your domain name, running mode and mounting path.
This is usually less likely to miss details related to WebSockets, static resources, upload directories, or SPA fallback pages than handwriting a configuration from scratch.
This is usually less likely to miss details related to `/files/`, WebSockets, static resources, upload directories, or SPA fallback pages than handwriting a configuration from scratch.
:::warning Note
`/files/` is an application route that must pass through NocoBase authorization. Do not handle it as a static directory or let it fall through to the SPA fallback. Forward it to the NocoBase backend and place the rule before `location /` and other front-end fallback rules.
If `APP_PUBLIC_PATH=/nocobase/` is configured, also forward `/nocobase/files/`. Keep the root-level `/files/` rule for compatibility with existing file URLs.
:::
## How to handle HTTPS
+5
View File
@@ -59,6 +59,11 @@
"label": "Campo de adjunto",
"link": "/file-manager/field-attachment"
},
{
"type": "custom-link",
"label": "URL estable",
"link": "/file-manager/stable-url"
},
{
"type": "custom-link",
"label": "Vista previa de archivos",
+57
View File
@@ -0,0 +1,57 @@
---
pkg: '@nocobase/plugin-file-manager'
title: "URL estable (URL proxy)"
description: "Explica el formato, los permisos, las redirecciones y el comportamiento de las URL estables de archivos en NocoBase."
keywords: "URL estable,URL proxy,URL permanente,acceso a archivos,vista previa de Office,NocoBase"
---
# URL estable
Los archivos administrados por un motor de almacenamiento se abren mediante una **URL estable**. NocoBase comprueba el registro y los permisos, y después redirige a la URL real generada por el almacenamiento.
## Formato
```text
/files/<app>/<dataSource>/<collection>/<id><extname>
```
Con `APP_PUBLIC_PATH=/nocobase`, la ruta comienza por `/nocobase/files/`. El ID y la extensión no pueden modificarse después de crear el archivo, por lo que la URL permanece estable mientras exista el registro.
| Uso | URL | Comportamiento |
|---|---|---|
| Abrir | `/files/.../42.pdf` | Comprueba permisos y redirige al archivo |
| Vista previa | `/files/.../42.png?preview=1` | Redirige a la miniatura o vista previa |
| Descargar | `/files/.../42.pdf?download=1` | Redirige con semántica de descarga |
| Office | `/files/.../42.xlsx?temporaryAccessToken=...` | Acceso temporal para Office Online Viewer |
## Comportamiento en NocoBase
- Los campos de adjuntos, las tablas de archivos y la [HTTP API](./http-api.md) devuelven la URL estable en `url` y `preview`
- Markdown guarda la URL estable y admite almacenamiento privado S3, OSS, COS o S3 Pro
- Un campo URL de adjunto conserva las URL externas introducidas manualmente, pero usa la URL estable para archivos administrados
- Las vistas previas normales usan la sesión y los permisos actuales de NocoBase
- Un formulario público solo permite ver los archivos subidos durante la sesión limitada de ese formulario
## Vista previa de Office
Microsoft Office Online Viewer no puede usar la cookie del usuario. Al abrir la vista previa, NocoBase comprueba primero el permiso y emite una URL temporal vinculada al archivo. Dura 10 minutos de forma predeterminada y puede configurarse entre 5 y 10 minutos con `TEMPORARY_FILE_ACCESS_EXPIRES_IN`.
No guardes esa URL temporal en campos, Markdown ni datos de negocio, y no la uses como enlace compartido.
## Precauciones
- Estable no significa público; el destinatario todavía necesita permisos
- Al eliminar o mover el registro a otro contexto, la URL anterior deja de funcionar
- La respuesta es una redirección `302`; los clientes deben seguirla
- No guardes `302 Location` ni `temporaryAccessToken`
- El proxy inverso debe reenviar a NocoBase la ruta `/files/` situada bajo `APP_PUBLIC_PATH`. En despliegues bajo una subruta, también debe conservarse la ruta compatible `/files/` en la raíz. Las configuraciones generadas por la CLI de NocoBase incluyen ambas reglas automáticamente
- En despliegues donde las páginas acceden a la API entre orígenes (`API_BASE_URL` apunta a otro origen), debes añadir el origen de la página a `CORS_ORIGIN_WHITELIST`. De lo contrario, la cookie de inicio de sesión nunca se almacenará y las URL estables devolverán `403` por falta de credenciales. Consulta [Variables de entorno](../get-started/installation/env.md#api_base_url)
- Usa un `hostname` diferente para cada servicio NocoBase independiente, en vez de diferenciarlos únicamente por el puerto. Las cookies del navegador no se aíslan por puerto; consulta [Despliegue en producción](../get-started/deployment/production.md)
- Las subaplicaciones de un mismo despliegue de NocoBase se distinguen por el nombre de la aplicación y no necesitan hostnames separados. Sin embargo, un servicio independiente en otro puerto sigue necesitando aislamiento por hostname si contiene una aplicación principal o subaplicación con el mismo nombre
## Enlaces relacionados
- [HTTP API](./http-api.md) — Subir y consultar archivos
- [Vista previa de archivos](./file-preview/index.md) — Formatos de vista previa
- [Vista previa de Office](./file-preview/ms-office.md) — Configurar Office Online Viewer
- [Motores de almacenamiento](./storage/index.md) — Configurar el almacenamiento
@@ -2,12 +2,34 @@
Al desplegar NocoBase en un entorno de producción, la instalación de dependencias puede ser complicada debido a las diferencias en los métodos de construcción entre distintos sistemas y entornos. Para una experiencia funcional completa, le recomendamos desplegarlo con **Docker**. Si su entorno de sistema no puede usar Docker, también puede desplegarlo utilizando **create-nocobase-app**.
:::warning
:::warning Atención
No se recomienda desplegar directamente desde el código fuente en un entorno de producción. El código fuente tiene muchas dependencias, es de gran tamaño y una compilación completa exige altos requisitos de CPU y memoria. Si realmente necesita desplegar desde el código fuente, le sugerimos construir primero una imagen Docker personalizada y luego proceder con el despliegue.
:::
:::warning Atención
Si despliega varios servicios NocoBase independientes, utilice un `hostname` diferente para cada servicio, como subdominios distintos. No diferencie los servicios únicamente por el puerto, por ejemplo `https://example.com:13000` y `https://example.com:14000`.
NocoBase usa cookies para mantener el estado de inicio de sesión y los [permisos de acceso a archivos](../../file-manager/stable-url.md). Los navegadores no aíslan las cookies por puerto, por lo que los servicios en distintos puertos bajo el mismo `hostname` pueden compartir cookies con el mismo nombre. Esto puede sobrescribir el estado de inicio de sesión o provocar errores de autorización al previsualizar o descargar archivos.
Las subaplicaciones del mismo despliegue de NocoBase no están sujetas a esta restricción. Las cookies de inicio de sesión se distinguen por el nombre de la aplicación, por lo que la aplicación principal y las subaplicaciones con nombres diferentes pueden compartir un mismo `hostname`.
Sin embargo, los servicios independientes todavía deben aislarse. Si otro servicio NocoBase se ejecuta en otro puerto bajo el mismo `hostname` y contiene una aplicación principal o subaplicación con el mismo nombre, las cookies aún pueden entrar en conflicto.
Utilice direcciones como `app1.example.com` y `app2.example.com`, y diríjalas a los distintos servicios NocoBase mediante Nginx o Caddy.
:::
## Frontend separado / Acceso API entre orígenes
Se recomienda mantener las páginas y la API en el mismo origen: utilice un proxy inverso bajo el mismo dominio para reenviar `${APP_PUBLIC_PATH}api/` y `${APP_PUBLIC_PATH}files/` al servicio NocoBase, y deje `API_BASE_URL` vacío.
Si las páginas deben acceder a la API entre orígenes (`API_BASE_URL` apunta a otro origen), añada el origen de la página a `CORS_ORIGIN_WHITELIST`. De lo contrario, el navegador ignorará `Set-Cookie` en las respuestas de la API, la cookie de inicio de sesión no se almacenará y la previsualización y descarga mediante URL de archivo estables fallarán en la autorización.
Tenga en cuenta también que las cookies se almacenan por `hostname`: si las páginas y la API usan dominios completamente distintos, las solicitudes a `/files/` desde el dominio de la página no llevarán la cookie de inicio de sesión almacenada bajo el dominio de la API. En esos despliegues debe usarse un proxy inverso del mismo origen. Consulte [Variables de entorno](../installation/env.md#api_base_url).
## Proceso de Despliegue
Para el despliegue en un entorno de producción, puede consultar los pasos de instalación y actualización existentes.
@@ -39,4 +61,4 @@ En un entorno de producción, se recomienda gestionar los recursos estáticos co
Según el método de instalación, puede usar los siguientes comandos para gestionar el proceso de NocoBase:
- [docker compose](./common-commands/docker-compose.md)
- [pm2](./common-commands/pm2.md)
- [pm2](./common-commands/pm2.md)
@@ -94,6 +94,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` permite que el contenedor de Caddy acceda al servicio `app` mediante la red de Compose
- `./storage` debe montarse tanto en `app` como en `caddy` para compartir la configuración del proxy, los recursos estáticos y los archivos subidos
- El contenedor `caddy` debe esperar a que se genere `nocobase.caddy` y luego enlazarlo a `/etc/caddy/Caddyfile` con `ln -sf`
- La configuración generada reenvía a NocoBase tanto la ruta `/files/` bajo `APP_PUBLIC_PATH` como la ruta `/files/` en la raíz para permitir vistas previas y descargas autenticadas
- Expón al host solo el puerto del contenedor de Caddy. Para pruebas, puedes empezar con `13000:80`; en producción, normalmente se exponen directamente los puertos `80` y `443` del host, mientras que el servicio `app` no necesita exponer su puerto al host
## Si usas Caddy local en el host
@@ -169,6 +170,8 @@ sudo systemctl reload caddy
Si tu Caddy local no usa `/etc/caddy/Caddyfile`, sustituye la ruta del enlace por tu propia ruta de configuración. En la mayoría de los casos es más seguro mantener `nocobase.caddy` como archivo de entrada principal en lugar de copiar su contenido manualmente.
Si mantienes Caddy por tu cuenta en lugar de usar la configuración generada, asegúrate de que `/files/*` y la ruta correspondiente bajo `APP_PUBLIC_PATH` se reenvíen a NocoBase antes de las reglas de fallback de la SPA. Consulta [Proxy inverso con Caddy](../../nocobase-cli/production/reverse-proxy/caddy.md) para ver un ejemplo completo.
## Enlaces relacionados
- [Instalación con Docker (Nginx integrado)](./docker.mdx) — Empieza con el despliegue de un solo contenedor
@@ -95,6 +95,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` permite que el contenedor de Nginx acceda al servicio `app` mediante la red de Compose
- `./storage` debe montarse tanto en `app` como en `nginx` para compartir la configuración del proxy, los recursos estáticos y los archivos subidos
- El contenedor `nginx` debe esperar a que se genere `nocobase.conf` y luego enlazarlo a `/etc/nginx/conf.d/default.conf` con `ln -sf`
- La configuración generada reenvía a NocoBase tanto la ruta `/files/` bajo `APP_PUBLIC_PATH` como la ruta `/files/` en la raíz para permitir vistas previas y descargas autenticadas
- Si usas un contenedor externo de Nginx, deja que el contenedor `nginx` gestione el mapeo del puerto del host. Para pruebas, puedes empezar con `13000:80`; en producción, normalmente se exponen directamente los puertos `80` y `443` del host, mientras que el servicio `app` no necesita exponer su puerto al host
## Si usas Nginx local en el host
@@ -170,6 +171,8 @@ sudo systemctl reload nginx
Si tu Nginx local no usa el directorio `conf.d`, sustituye la ruta del enlace por tu propia ruta de configuración. En la mayoría de los casos es más seguro mantener `nocobase.conf` como un archivo incluido desde el contexto `http {}` en lugar de copiar su contenido manualmente.
Si mantienes Nginx por tu cuenta en lugar de usar la configuración generada, asegúrate de que `/files/` y la ruta correspondiente bajo `APP_PUBLIC_PATH` se reenvíen a NocoBase antes de las reglas de fallback de la SPA. Consulta [Proxy inverso con Nginx](../../nocobase-cli/production/reverse-proxy/nginx.md) para ver un ejemplo completo.
## Enlaces relacionados
- [Instalación con Docker (Nginx integrado)](./docker.mdx) — Empieza con el despliegue de un solo contenedor
@@ -628,7 +628,7 @@ Si usas la imagen con Nginx integrado, normalmente es mejor no exponer `13000` d
La siguiente configuración proxy las solicitudes del dominio hacia `http://127.0.0.1:13000/`:
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # Sustituye your_domain.com por tu dominio
@@ -659,6 +659,8 @@ server {
Si también quieres habilitar HTTPS, configura `443` y el certificado en el Nginx del host. El contenedor de NocoBase no necesita gestionar certificados por separado.
El bloque `location /` de esta configuración en la ruta raíz también reenvía `/api/`, `/ws` y `/files/`. Si separas los recursos estáticos de las rutas de la aplicación, asegúrate de que `/files/` siga reenviándose a NocoBase y no se trate como un directorio estático.
### Despliegue en subruta
Si quieres desplegar la aplicación en una subruta, por ejemplo `https://your_domain.com/nocobase/`, primero configura la variable de entorno `APP_PUBLIC_PATH`:
@@ -675,7 +677,7 @@ Mantén el `/` inicial y final en la ruta. Una vez configurado, la URL de la apl
Después configura el Nginx del host con el mismo proxy de subruta:
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # Sustituye your_domain.com por tu dominio
@@ -701,10 +703,32 @@ server {
send_timeout 600;
proxy_buffering off;
}
# Mantén la compatibilidad con las URL de acceso a archivos en la raíz.
location ^~ /files/ {
proxy_pass http://127.0.0.1:13000;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $upstream_x_forwarded_proto;
proxy_set_header Host $final_host;
proxy_set_header Referer $http_referer;
proxy_set_header User-Agent $http_user_agent;
add_header Cache-Control "no-cache, no-store" always;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
}
}
```
La clave es que `APP_PUBLIC_PATH` y la ruta en `proxy_pass` deben mantenerse coherentes. Si falta `/nocobase/` en cualquiera de los dos lados, normalmente los recursos estáticos y el enrutamiento no funcionarán correctamente.
Ten en cuenta estos puntos:
- `APP_PUBLIC_PATH` y la ruta en `proxy_pass` deben mantenerse coherentes. Si falta `/nocobase/` en cualquiera de los dos lados, normalmente los recursos estáticos y el enrutamiento no funcionarán correctamente
- `/nocobase/files/` se reenvía mediante `location /nocobase/`; la ruta compatible `/files/` en la raíz debe reenviarse a NocoBase por separado
### Otras opciones
@@ -86,6 +86,39 @@ API_BASE_PATH=/api/
### API_BASE_URL
URL base que el frontend utiliza para acceder a la API de NocoBase. Está vacía por defecto, lo que significa que se usa `${APP_PUBLIC_PATH}api/` en el mismo origen.
```bash
API_BASE_URL=
```
Solo configúrela con la dirección completa de la API cuando las páginas y el servicio de API estén en orígenes distintos (protocolo, dominio o puerto diferentes):
```bash
API_BASE_URL=https://api.example.com/api/
```
:::warning{title="Despliegues entre orígenes"}
NocoBase utiliza cookies para mantener el estado de inicio de sesión y autorizar el acceso a las [URL estables de archivos](../../file-manager/stable-url.md). Cuando `API_BASE_URL` apunta a un origen distinto del de las páginas:
- Debe añadirse el origen de la página a [`CORS_ORIGIN_WHITELIST`](#cors_origin_whitelist). De lo contrario, el navegador ignorará `Set-Cookie` en las respuestas de la API, la cookie de inicio de sesión no se almacenará y las funciones que dependen de cookies, como la vista previa y la descarga de archivos, fallarán con `403`.
- Las cookies se almacenan por `hostname`. Si las páginas y la API usan dominios completamente distintos, las solicitudes a URL estables bajo `/files/` desde el dominio de la página no enviarán la cookie de inicio de sesión guardada bajo el dominio de la API, por lo que el acceso al archivo seguirá fallando.
Se recomienda servir las páginas y la API desde el mismo origen mediante un proxy inverso y dejar `API_BASE_URL` vacío.
:::
### CORS_ORIGIN_WHITELIST
Lista blanca de orígenes autorizados a acceder a la API entre orígenes con credenciales (cookies). Separe varios orígenes con comas. Está vacía por defecto.
```bash
CORS_ORIGIN_WHITELIST=https://www.example.com,https://admin.example.com
```
- Cuando no está configurada, solo las solicitudes del mismo origen se consideran de confianza; las solicitudes entre orígenes aún pueden llamar a la API de forma anónima, pero el navegador no puede leer ni escribir cookies para ellas.
- Cuando está configurada, los orígenes incluidos reciben un `Access-Control-Allow-Origin` que refleja exactamente el origen y `Access-Control-Allow-Credentials: true`, lo que permite al navegador enviar y almacenar cookies de inicio de sesión en solicitudes entre orígenes.
- La API de inicio de sesión valida el `Origin` y el `Referer` de la solicitud; las solicitudes de inicio de sesión entre orígenes procedentes de orígenes fuera de la lista blanca se rechazan con `403`.
### CLUSTER_MODE
> `v1.6.0+`
@@ -69,6 +69,16 @@ Si se encuentra atascado aquí "¿Por qué necesita `nb app autostart`", simplem
- Si vas a conectarte al proxy inverso, `appPort` se ha guardado en env
- Si estás listo para abrirlo oficialmente al mundo exterior, ya has planificado el nombre de dominio, el puerto de entrada y la solución HTTPS.
:::warning Atención
Use un `hostname` diferente, como un subdominio independiente, para cada servicio NocoBase autónomo. No diferencie los servicios únicamente por el puerto. Las cookies del navegador no se aíslan por puerto, por lo que los servicios bajo el mismo `hostname` pueden sobrescribir el estado de inicio de sesión y afectar la autorización de las [URL estables](../../file-manager/stable-url.md).
Las subaplicaciones de un mismo despliegue de NocoBase se distinguen por el nombre de la aplicación y no necesitan hostnames separados. Sin embargo, si otro servicio NocoBase independiente se ejecuta en otro puerto bajo el mismo `hostname` y contiene una aplicación principal o subaplicación con el mismo nombre, las cookies aún pueden entrar en conflicto.
Por ejemplo, utilice `app1.example.com` y `app2.example.com` en lugar de `example.com:13000` y `example.com:14000`.
:::
Si no ha completado la instalación de CLI o la inicialización del entorno, regrese a [Instalación mediante CLI (recomendado)] (../installation/cli.md).
Si el comando indica que falta env `appPort`, primero ejecute [`nb env update`](../../api/cli/env/update.md) para completarlo.
@@ -124,7 +124,7 @@ Si desea compensar la configuración a nivel de sitio de Caddy, como encabezados
Si su aplicación no está alojada en CLI o desea explícitamente mantener usted mismo la configuración completa de Caddy, también puede escribirla a mano.
Sin embargo, para NocoBase, la entrada del entorno de producción generalmente no es solo un simple `reverse_proxy`. Además de reenviar solicitudes de API a la aplicación de backend, una configuración de Caddy completa y funcional generalmente también necesita manejar el directorio de carga, los recursos estáticos de front-end, el enrutamiento `.well-known`, WebSocket y la página alternativa de SPA.
Sin embargo, para NocoBase, la entrada del entorno de producción generalmente no es solo un simple `reverse_proxy`. Además de reenviar solicitudes de API a la aplicación backend, una configuración completa y funcional de Caddy generalmente debe gestionar el directorio de carga, los recursos estáticos de front-end, la ruta de acceso a archivos `/files/`, el enrutamiento `.well-known`, WebSocket y las páginas alternativas de la SPA.
Tomando `test2` como ejemplo, los directorios clave relacionados con Caddy generalmente incluyen:
@@ -139,6 +139,7 @@ En otras palabras, la configuración escrita a mano normalmente debe cubrir al m
- `dist`: exponer el directorio de productos de compilación front-end
- `oauth well-known`: Manejar rutas de descubrimiento de OAuth
- `openid well-known`: Manejar rutas de descubrimiento de OpenID
- `files`: reenviar las solicitudes de acceso a archivos bajo `/files/` a la aplicación backend
- `api`: reenviar la solicitud `/api/` a la aplicación backend
- `ws`: reenvía solicitudes de WebSocket a la aplicación backend
- `spa v2`: proporciona entrada frontal y página de retorno para `/v/`
@@ -187,6 +188,10 @@ c.local.nocobase.com {
reverse_proxy host.docker.internal:56575
}
handle /files/* {
reverse_proxy host.docker.internal:56575
}
handle /api/* {
reverse_proxy host.docker.internal:56575
}
@@ -249,7 +254,15 @@ Un enfoque más prudente suele ser:
2. Confirme la estructura de enrutamiento y la ruta real según los resultados generados.
3. Luego realice ajustes manuales según su nombre de dominio, modo de ejecución y ruta de montaje.
Por lo general, es menos probable que se pierdan detalles relacionados con WebSockets, recursos estáticos, directorios de carga, rutas `.well-known` o páginas de respaldo de SPA que escribir a mano una configuración desde cero.
Por lo general, es menos probable que se pierdan detalles relacionados con `/files/`, WebSockets, recursos estáticos, directorios de carga, rutas `.well-known` o páginas de respaldo de la SPA que al escribir una configuración desde cero.
:::warning Atención
`/files/` es una ruta de la aplicación que debe pasar por la autorización de NocoBase. No la trates como un directorio estático ni permitas que llegue al fallback de la SPA. Reenvíala al backend de NocoBase y coloca la regla antes de `handle_path /*` y de otras reglas de fallback del front-end.
Si se configura `APP_PUBLIC_PATH=/nocobase/`, reenvía también `/nocobase/files/*`. Conserva la regla raíz `/files/*` para mantener la compatibilidad con las URL de archivos existentes.
:::
## Verificar y recargar la configuración
@@ -9,7 +9,7 @@ keywords: "NocoBase, nb proxy nginx, nb proxy caddy, proxy inverso, Nginx, Caddy
Este artículo solo se aplica a las aplicaciones instaladas con `nb init`.
En NocoBase, el proxy inverso del entorno de producción hace más que simplemente reenviar solicitudes al proceso de solicitud. A menudo, los detalles de WebSockets, subrutas, recursos estáticos de front-end, directorios de carga y páginas alternativas de SPA también se manejan al mismo tiempo.
En NocoBase, el proxy inverso del entorno de producción hace más que simplemente reenviar solicitudes al proceso de la aplicación. También debe gestionar WebSockets, subrutas, recursos estáticos de front-end, directorios de carga, la ruta de acceso a archivos `/files/` y las páginas alternativas de la SPA.
La función de `nb proxy` es recopilar estos detalles que fácilmente se pasan por alto en un conjunto estable de entradas de comando.
@@ -122,7 +122,7 @@ Si desea agregar configuración de Nginx a nivel de sitio, como limitación actu
Si su aplicación no está alojada en CLI o desea explícitamente mantener usted mismo la configuración completa de Nginx, también puede escribirla a mano.
Sin embargo, para NocoBase, el proxy inverso de producción suele ser más que un simple `proxy_pass`. Además de reenviar solicitudes de API a la aplicación de backend, una configuración completa y utilizable generalmente necesita manejar el directorio de carga, los recursos estáticos de front-end, WebSocket, la ruta `.well-known` y la página alternativa de SPA.
Sin embargo, para NocoBase, el proxy inverso de producción suele ser más que un simple `proxy_pass`. Además de reenviar solicitudes de API a la aplicación backend, una configuración completa y utilizable generalmente debe gestionar el directorio de carga, los recursos estáticos de front-end, la ruta de acceso a archivos `/files/`, WebSocket, la ruta `.well-known` y las páginas alternativas de la SPA.
Tomando `test2` como ejemplo, los archivos y directorios clave relacionados con Nginx generalmente incluyen:
@@ -138,6 +138,7 @@ En otras palabras, la configuración escrita a mano normalmente debe cubrir al m
- `uploads`: exponer el directorio de carga a través de `alias`
- `dist`: exponer el directorio de productos de compilación front-end a través de `alias`
- `well-known`: Manejar rutas de descubrimiento relacionadas con OAuth/OpenID
- `files`: reenviar las solicitudes de acceso a archivos bajo `/files/` a la aplicación backend
- `api`: reenviar la solicitud `/api/` a la aplicación backend
- `ws`: reenvía solicitudes de WebSocket a la aplicación backend
- `spa`: proporciona entrada frontal y `try_files` respaldo para `/` y `/v/`
@@ -180,6 +181,11 @@ server {
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /files/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /api/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
@@ -229,7 +235,15 @@ Un enfoque más prudente suele ser:
2. Confirme la estructura de enrutamiento y la ruta real según los resultados generados.
3. Luego realice ajustes manuales según su nombre de dominio, modo de ejecución y ruta de montaje.
Por lo general, es menos probable que se pierdan detalles relacionados con WebSockets, recursos estáticos, directorios de carga o páginas de respaldo de SPA que escribir a mano una configuración desde cero.
Por lo general, es menos probable que se pierdan detalles relacionados con `/files/`, WebSockets, recursos estáticos, directorios de carga o páginas de respaldo de la SPA que al escribir una configuración desde cero.
:::warning Atención
`/files/` es una ruta de la aplicación que debe pasar por la autorización de NocoBase. No la trates como un directorio estático ni permitas que llegue al fallback de la SPA. Reenvíala al backend de NocoBase y coloca la regla antes de `location /` y de otras reglas de fallback del front-end.
Si se configura `APP_PUBLIC_PATH=/nocobase/`, reenvía también `/nocobase/files/`. Conserva la regla raíz `/files/` para mantener la compatibilidad con las URL de archivos existentes.
:::
## Cómo manejar HTTPS
+5
View File
@@ -59,6 +59,11 @@
"label": "Champ pièce jointe",
"link": "/file-manager/field-attachment"
},
{
"type": "custom-link",
"label": "URL stable",
"link": "/file-manager/stable-url"
},
{
"type": "custom-link",
"label": "Aperçu de fichiers",
+57
View File
@@ -0,0 +1,57 @@
---
pkg: '@nocobase/plugin-file-manager'
title: "URL stable (URL proxy)"
description: "Explique le format, les autorisations, les redirections et le comportement des URL de fichiers stables dans NocoBase."
keywords: "URL stable,URL proxy,URL permanente,accès aux fichiers,aperçu Office,NocoBase"
---
# URL stable
Les fichiers gérés par un moteur de stockage sont accessibles via une **URL stable**. NocoBase vérifie l'enregistrement et les autorisations, puis redirige vers l'URL réelle générée par le stockage.
## Format
```text
/files/<app>/<dataSource>/<collection>/<id><extname>
```
Avec `APP_PUBLIC_PATH=/nocobase`, le chemin commence par `/nocobase/files/`. L'ID et l'extension ne peuvent pas être modifiés après la création, ce qui garde l'URL stable tant que l'enregistrement existe.
| Usage | URL | Comportement |
|---|---|---|
| Ouvrir | `/files/.../42.pdf` | Vérifie les droits et redirige vers le fichier |
| Aperçu | `/files/.../42.png?preview=1` | Redirige vers l'aperçu ou la miniature |
| Télécharger | `/files/.../42.pdf?download=1` | Redirige avec une sémantique de téléchargement |
| Office | `/files/.../42.xlsx?temporaryAccessToken=...` | Accès temporaire pour Office Online Viewer |
## Comportement dans NocoBase
- Les champs pièce jointe, les tables de fichiers et l'[HTTP API](./http-api.md) renvoient des URL stables dans `url` et `preview`
- Markdown enregistre l'URL stable et prend en charge les stockages privés S3, OSS, COS et S3 Pro
- Le champ URL de pièce jointe conserve les URL externes saisies manuellement et utilise l'URL stable pour les fichiers gérés
- Les aperçus classiques utilisent la session et les autorisations NocoBase actuelles
- Un formulaire public limite l'accès aux fichiers envoyés pendant la session actuelle du formulaire
## Aperçu Office
Microsoft Office Online Viewer ne peut pas utiliser le cookie NocoBase de l'utilisateur. À l'ouverture, NocoBase vérifie d'abord l'autorisation, puis émet une URL temporaire liée au fichier. Elle est valable 10 minutes par défaut et peut être réglée de 5 à 10 minutes avec `TEMPORARY_FILE_ACCESS_EXPIRES_IN`.
N'enregistrez pas cette URL dans un champ, du Markdown ou des données métier, et ne l'utilisez pas comme lien de partage.
## Précautions
- Stable ne signifie pas public ; le destinataire a toujours besoin d'une autorisation
- La suppression ou le déplacement de l'enregistrement invalide l'ancienne URL
- La réponse est une redirection `302` que le client doit suivre
- Ne conservez pas `302 Location` ni `temporaryAccessToken`
- Le proxy inverse doit transmettre à NocoBase la route `/files/` située sous `APP_PUBLIC_PATH`. Pour un déploiement dans un sous-chemin, conservez également la route compatible `/files/` à la racine. Les configurations générées par la CLI NocoBase incluent automatiquement ces deux règles
- Dans les déploiements où les pages accèdent à l'API en cross-origin (`API_BASE_URL` pointe vers une autre origine), vous devez ajouter l'origine des pages à `CORS_ORIGIN_WHITELIST`. Sinon, le cookie de connexion n'est jamais enregistré et les URL stables renvoient `403` faute d'identifiants. Voir [Variables d'environnement](../get-started/installation/env.md#api_base_url)
- Utilisez un `hostname` différent pour chaque service NocoBase indépendant au lieu de les distinguer uniquement par leur port. Les cookies du navigateur ne sont pas isolés par port ; consultez [Déploiement en production](../get-started/deployment/production.md)
- Les sous-applications d'un même déploiement NocoBase sont distinguées par leur nom d'application et ne nécessitent pas de hostnames séparés. Un service indépendant exécuté sur un autre port doit toutefois être isolé par hostname s'il contient une application principale ou une sous-application portant le même nom
## Liens associés
- [HTTP API](./http-api.md) — Envoyer et interroger des fichiers
- [Aperçu de fichiers](./file-preview/index.md) — Formats d'aperçu pris en charge
- [Aperçu Office](./file-preview/ms-office.md) — Configurer Office Viewer
- [Moteurs de stockage](./storage/index.md) — Configurer le stockage
@@ -2,12 +2,34 @@
Lors du déploiement de NocoBase en environnement de production, l'installation des dépendances peut s'avérer complexe en raison des différentes méthodes de construction selon les systèmes et les environnements. Pour une expérience fonctionnelle complète, nous vous recommandons d'utiliser **Docker** pour le déploiement. Si votre environnement système ne permet pas l'utilisation de Docker, vous pouvez également déployer NocoBase avec **create-nocobase-app**.
:::warning
:::warning Attention
Il n'est pas recommandé de déployer directement à partir du code source en environnement de production. Le code source comporte de nombreuses dépendances, est volumineux, et une compilation complète exige des ressources CPU et mémoire élevées. Si vous devez impérativement déployer à partir du code source, nous vous suggérons de construire d'abord une image Docker personnalisée, puis de la déployer.
:::
:::warning Attention
Si vous déployez plusieurs services NocoBase indépendants, utilisez un `hostname` différent pour chaque service, par exemple des sous-domaines distincts. Ne distinguez pas les services uniquement par leur port, comme `https://example.com:13000` et `https://example.com:14000`.
NocoBase utilise des cookies pour conserver l'état de connexion et les [autorisations d'accès aux fichiers](../../file-manager/stable-url.md). Les navigateurs n'isolent pas les cookies par port. Des services exécutés sur différents ports sous le même `hostname` peuvent donc partager des cookies portant le même nom, écraser l'état de connexion ou provoquer des échecs d'autorisation lors de l'aperçu et du téléchargement de fichiers.
Les sous-applications d'un même déploiement NocoBase ne sont pas concernées par cette restriction. Les cookies de connexion sont distingués par le nom de l'application, de sorte que l'application principale et les sous-applications portant des noms différents peuvent partager un même `hostname`.
Les services indépendants doivent toutefois rester isolés. Si un autre service NocoBase s'exécute sur un autre port sous le même `hostname` et contient une application principale ou une sous-application portant le même nom, les cookies peuvent encore entrer en conflit.
Utilisez par exemple `app1.example.com` et `app2.example.com`, puis acheminez-les vers les différents services NocoBase avec Nginx ou Caddy.
:::
## Frontend séparé / Accès API cross-origin
Il est recommandé de conserver les pages et l'API sur la même origine : utilisez un proxy inverse sous le même domaine pour transférer `${APP_PUBLIC_PATH}api/` et `${APP_PUBLIC_PATH}files/` vers le service NocoBase, et laissez `API_BASE_URL` vide.
Si les pages doivent accéder à l'API en cross-origin (`API_BASE_URL` pointe vers une autre origine), ajoutez l'origine des pages à `CORS_ORIGIN_WHITELIST`. Sinon, le navigateur ignorera `Set-Cookie` dans les réponses de l'API, le cookie de connexion ne sera pas enregistré et l'aperçu ainsi que le téléchargement via les URL de fichiers stables échoueront à l'autorisation.
Notez également que les cookies sont stockés par `hostname` : si les pages et l'API utilisent des domaines totalement différents, les requêtes vers `/files/` depuis le domaine des pages n'enverront pas le cookie de connexion stocké sous le domaine de l'API. Ce type de déploiement doit être remplacé par un proxy inverse same-origin. Voir [Variables d'environnement](../installation/env.md#api_base_url).
## Processus de déploiement
Pour le déploiement en environnement de production, vous pouvez vous référer aux étapes d'installation et de mise à niveau existantes.
@@ -39,4 +61,4 @@ En environnement de production, il est recommandé de confier la gestion des res
Selon la méthode d'installation, vous pouvez utiliser les commandes suivantes pour gérer le processus NocoBase :
- [docker compose](./common-commands/docker-compose.md)
- [pm2](./common-commands/pm2.md)
- [pm2](./common-commands/pm2.md)
@@ -94,6 +94,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` permet au conteneur Caddy d'accéder au service `app` via le réseau Compose
- `./storage` doit être monté dans `app` et `caddy` afin de partager la configuration du proxy, les ressources statiques et les fichiers téléversés
- Le conteneur `caddy` doit attendre que `nocobase.caddy` soit généré, puis créer un lien vers `/etc/caddy/Caddyfile` avec `ln -sf`
- La configuration générée transmet à NocoBase la route `/files/` sous `APP_PUBLIC_PATH` ainsi que la route `/files/` à la racine, afin d'assurer l'aperçu et le téléchargement authentifiés des fichiers
- Exposez uniquement le port du conteneur Caddy à l'hôte. Pour les tests, vous pouvez commencer avec `13000:80`; en production, exposez généralement directement les ports `80` et `443` de l'hôte, tandis que le service `app` n'a pas besoin d'exposer son port à l'hôte
## Si vous utilisez un Caddy local sur l'hôte
@@ -169,6 +170,8 @@ sudo systemctl reload caddy
Si votre Caddy local n'utilise pas `/etc/caddy/Caddyfile`, remplacez la cible du lien par votre propre chemin de configuration. En général, il est plus sûr de garder `nocobase.caddy` comme fichier d'entrée principal plutôt que d'en recopier le contenu manuellement.
Si vous gérez Caddy vous-même au lieu d'utiliser la configuration générée, vérifiez que `/files/*` et la route correspondante sous `APP_PUBLIC_PATH` sont transmises à NocoBase avant les règles de fallback de la SPA. Consultez [Proxy inverse Caddy](../../nocobase-cli/production/reverse-proxy/caddy.md) pour un exemple complet.
## Liens associés
- [Installation Docker (Nginx intégré)](./docker.mdx) — Commencez par le déploiement à conteneur unique
@@ -95,6 +95,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` permet au conteneur Nginx d'accéder au service `app` via le réseau Compose
- `./storage` doit être monté dans `app` et `nginx` afin de partager la configuration du proxy, les ressources statiques et les fichiers téléversés
- Le conteneur `nginx` doit attendre que `nocobase.conf` soit généré, puis créer un lien vers `/etc/nginx/conf.d/default.conf` avec `ln -sf`
- La configuration générée transmet à NocoBase la route `/files/` sous `APP_PUBLIC_PATH` ainsi que la route `/files/` à la racine, afin d'assurer l'aperçu et le téléchargement authentifiés des fichiers
- Si vous utilisez un conteneur Nginx externe, laissez le conteneur `nginx` gérer le mappage du port hôte. Pour les tests, vous pouvez commencer avec `13000:80`; en production, exposez généralement directement les ports `80` et `443` de l'hôte, tandis que le service `app` n'a pas besoin d'exposer son port à l'hôte
## Si vous utilisez un Nginx local sur l'hôte
@@ -170,6 +171,8 @@ sudo systemctl reload nginx
Si votre Nginx local n'utilise pas le répertoire `conf.d`, remplacez la cible du lien par votre propre chemin de configuration. En général, il est plus sûr de garder `nocobase.conf` comme un fichier inclus depuis le contexte `http {}` plutôt que d'en recopier le contenu manuellement.
Si vous gérez Nginx vous-même au lieu d'utiliser la configuration générée, vérifiez que `/files/` et la route correspondante sous `APP_PUBLIC_PATH` sont transmises à NocoBase avant les règles de fallback de la SPA. Consultez [Proxy inverse Nginx](../../nocobase-cli/production/reverse-proxy/nginx.md) pour un exemple complet.
## Liens associés
- [Installation Docker (Nginx intégré)](./docker.mdx) — Commencez par le déploiement à conteneur unique
@@ -628,7 +628,7 @@ Si vous utilisez l'image avec Nginx intégré, il est généralement préférabl
La configuration suivante proxy les requêtes du domaine vers `http://127.0.0.1:13000/` :
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # Remplacez your_domain.com par votre domaine
@@ -659,6 +659,8 @@ server {
Si vous voulez aussi activer HTTPS, configurez `443` et le certificat dans le Nginx de l'hôte. Le conteneur NocoBase n'a pas besoin de gérer les certificats séparément.
Le bloc `location /` de cette configuration à la racine transmet également `/api/`, `/ws` et `/files/`. Si vous séparez les ressources statiques des routes de l'application, assurez-vous que `/files/` reste transmis à NocoBase et n'est pas traité comme un répertoire statique.
### Déploiement sous un sous-chemin
Si vous voulez déployer l'application sous un sous-chemin, par exemple `https://your_domain.com/nocobase/`, configurez d'abord la variable d'environnement `APP_PUBLIC_PATH` :
@@ -675,7 +677,7 @@ Conservez le `/` au début et à la fin du chemin. Une fois la configuration ter
Configurez ensuite le Nginx de l'hôte avec le même sous-chemin :
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # Remplacez your_domain.com par votre domaine
@@ -701,10 +703,32 @@ server {
send_timeout 600;
proxy_buffering off;
}
# Conserver la compatibilité avec les URL d'accès aux fichiers à la racine.
location ^~ /files/ {
proxy_pass http://127.0.0.1:13000;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $upstream_x_forwarded_proto;
proxy_set_header Host $final_host;
proxy_set_header Referer $http_referer;
proxy_set_header User-Agent $http_user_agent;
add_header Cache-Control "no-cache, no-store" always;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
}
}
```
Le point clé est que `APP_PUBLIC_PATH` et le chemin dans `proxy_pass` doivent rester cohérents. Si l'un des deux oublie `/nocobase/`, les ressources statiques et le routage risquent de ne pas fonctionner correctement.
Gardez ces points à l'esprit :
- `APP_PUBLIC_PATH` et le chemin dans `proxy_pass` doivent rester cohérents. Si l'un des deux oublie `/nocobase/`, les ressources statiques et le routage risquent de ne pas fonctionner correctement
- `/nocobase/files/` est transmis par `location /nocobase/` ; la route compatible `/files/` à la racine doit être transmise séparément à NocoBase
### Autres options
@@ -86,6 +86,39 @@ API_BASE_PATH=/api/
### API_BASE_URL
URL de base utilisée par le frontend pour accéder à l'API NocoBase. Elle est vide par défaut, ce qui signifie que `${APP_PUBLIC_PATH}api/` du même origin est utilisé.
```bash
API_BASE_URL=
```
Ne la configurez avec l'adresse complète de l'API que lorsque les pages et le service API sont sur des origins différents (protocole, domaine ou port différents) :
```bash
API_BASE_URL=https://api.example.com/api/
```
:::warning{title="Déploiements cross-origin"}
NocoBase utilise des cookies pour conserver l'état de connexion et autoriser l'accès aux [URL de fichiers stables](../../file-manager/stable-url.md). Lorsque `API_BASE_URL` pointe vers un origin différent de celui des pages :
- L'origin des pages doit être ajouté à [`CORS_ORIGIN_WHITELIST`](#cors_origin_whitelist). Sinon, le navigateur ignorera `Set-Cookie` dans les réponses API, le cookie de connexion ne sera pas enregistré et les fonctions dépendantes des cookies, comme l'aperçu et le téléchargement de fichiers, échoueront avec `403`.
- Les cookies sont stockés par `hostname`. Si les pages et l'API utilisent des domaines totalement différents, les requêtes vers les URL stables sous `/files/` depuis le domaine des pages n'enverront pas le cookie de connexion stocké sous le domaine de l'API ; l'accès au fichier échouera donc toujours.
Il est recommandé de servir les pages et l'API depuis le même origin via un proxy inverse et de laisser `API_BASE_URL` vide.
:::
### CORS_ORIGIN_WHITELIST
Liste blanche des origins autorisés à accéder à l'API en cross-origin avec des identifiants (cookies). Plusieurs origins sont séparés par des virgules. Vide par défaut.
```bash
CORS_ORIGIN_WHITELIST=https://www.example.com,https://admin.example.com
```
- Lorsqu'elle n'est pas configurée, seules les requêtes du même origin sont considérées comme fiables ; les requêtes cross-origin peuvent encore appeler l'API anonymement, mais le navigateur ne peut pas lire ni écrire de cookies pour elles.
- Lorsqu'elle est configurée, les origins de la liste blanche reçoivent un `Access-Control-Allow-Origin` qui reprend exactement l'origin ainsi que `Access-Control-Allow-Credentials: true`, ce qui permet au navigateur d'envoyer et de stocker les cookies de connexion sur les requêtes cross-origin.
- L'API de connexion valide les en-têtes `Origin` et `Referer` de la requête ; les requêtes de connexion cross-origin provenant d'origins hors liste blanche sont rejetées avec `403`.
### CLUSTER_MODE
> `v1.6.0+`
@@ -69,6 +69,16 @@ Si vous êtes bloqué ici "Pourquoi avez-vous besoin de `nb app autostart`", con
- Si vous allez vous connecter au proxy inverse, `appPort` a été enregistré dans env
- Si vous êtes prêt à l'ouvrir officiellement au monde extérieur, vous avez déjà prévu le nom de domaine, le port d'entrée et la solution HTTPS.
:::warning Attention
Utilisez un `hostname` différent, comme un sous-domaine séparé, pour chaque service NocoBase indépendant. Ne distinguez pas les services uniquement par leur port. Les cookies du navigateur ne sont pas isolés par port ; des services sous le même `hostname` peuvent donc écraser l'état de connexion et affecter l'autorisation des [URL stables](../../file-manager/stable-url.md).
Les sous-applications d'un même déploiement NocoBase sont distinguées par leur nom d'application et ne nécessitent pas de hostnames séparés. Toutefois, si un autre service NocoBase indépendant s'exécute sur un autre port sous le même `hostname` et contient une application principale ou une sous-application portant le même nom, les cookies peuvent encore entrer en conflit.
Utilisez par exemple `app1.example.com` et `app2.example.com` plutôt que `example.com:13000` et `example.com:14000`.
:::
Si vous n'avez pas terminé l'installation CLI ou l'initialisation de l'environnement, revenez à [Installation à l'aide de CLI (recommandé)] (../installation/cli.md).
Si la commande indique qu'il manque `appPort` env, exécutez d'abord [`nb env update`](../../api/cli/env/update.md) pour le remplir.
@@ -124,7 +124,7 @@ Si vous souhaitez compenser la configuration au niveau du site Caddy, telle que
Si votre application n'est pas hébergée par CLI ou si vous souhaitez explicitement conserver vous-même la configuration complète de Caddy, vous pouvez également l'écrire à la main.
Cependant, pour NocoBase, l'entrée de l'environnement de production n'est généralement pas un simple `reverse_proxy`. En plus de transmettre les requêtes API à l'application backend, une configuration Caddy complète et fonctionnelle doit généralement également gérer le répertoire de téléchargement, les ressources statiques frontales, le routage `.well-known`, WebSocket et la page de secours SPA.
Cependant, pour NocoBase, l'entrée de production ne se limite généralement pas à un simple `reverse_proxy`. En plus de transmettre les requêtes API à l'application backend, une configuration Caddy complète et fonctionnelle doit généralement gérer le répertoire de téléversement, les ressources statiques frontales, la route d'accès aux fichiers `/files/`, le routage `.well-known`, WebSocket et les pages de secours de la SPA.
En prenant `test2` comme exemple, les répertoires clés liés à Caddy incluent généralement :
@@ -139,6 +139,7 @@ En dautres termes, la configuration manuscrite doit généralement couvrir au
- `dist` : exposer le répertoire du produit de build front-end
- `oauth well-known` : gérer les chemins de découverte OAuth
- `openid well-known` : gérer les chemins de découverte OpenID
- `files` : transmettre les requêtes d'accès aux fichiers sous `/files/` à l'application backend
- `api` : transmettre la requête `/api/` à l'application backend
- `ws` : transmettre les requêtes WebSocket à l'application backend
- `spa v2` : fournit une page d'entrée et de retour frontale pour `/v/`
@@ -187,6 +188,10 @@ c.local.nocobase.com {
reverse_proxy host.docker.internal:56575
}
handle /files/* {
reverse_proxy host.docker.internal:56575
}
handle /api/* {
reverse_proxy host.docker.internal:56575
}
@@ -249,7 +254,15 @@ Une approche plus prudente est généralement la suivante :
2. Confirmez la structure de routage et le chemin réel en fonction des résultats générés.
3. Effectuez ensuite des ajustements manuels en fonction de votre nom de domaine, de votre mode d'exécution et du chemin de montage.
Il est généralement moins probable que des détails liés aux WebSockets, aux ressources statiques, aux répertoires de téléchargement, aux routes `.well-known` ou aux pages de secours SPA soient manqués plutôt que d'écrire manuellement une configuration à partir de zéro.
Il est généralement moins probable de manquer des détails liés à `/files/`, aux WebSockets, aux ressources statiques, aux répertoires de téléversement, aux routes `.well-known` ou aux pages de secours de la SPA que d'écrire une configuration à partir de zéro.
:::warning Attention
`/files/` est une route applicative qui doit passer par l'autorisation NocoBase. Ne la traitez pas comme un répertoire statique et ne la laissez pas atteindre le fallback de la SPA. Transmettez-la au backend NocoBase et placez la règle avant `handle_path /*` et les autres règles de fallback du front-end.
Si `APP_PUBLIC_PATH=/nocobase/` est configuré, transmettez également `/nocobase/files/*`. Conservez la règle `/files/*` à la racine pour assurer la compatibilité avec les URL de fichiers existantes.
:::
## Vérifier et recharger la configuration
@@ -9,7 +9,7 @@ keywords: "NocoBase, nb proxy nginx, nb proxy caddy, proxy inverse, Nginx, Caddy
Cet article s'applique uniquement aux applications installées à l'aide de `nb init`.
Dans NocoBase, le proxy inverse de l'environnement de production fait plus que simplement transmettre les demandes au processus de candidature. Souvent, les détails des WebSockets, des sous-chemins, des ressources statiques frontales, des répertoires de téléchargement et des pages de secours SPA sont également traités en même temps.
Dans NocoBase, le proxy inverse de production ne se contente pas de transmettre les requêtes au processus de l'application. Il doit aussi gérer les WebSockets, les sous-chemins, les ressources statiques frontales, les répertoires de téléversement, la route d'accès aux fichiers `/files/` et les pages de secours de la SPA.
La fonction de `nb proxy` est de collecter ces détails facilement manqués dans un ensemble stable d'entrées de commande.
@@ -122,7 +122,7 @@ Si vous souhaitez ajouter une configuration Nginx au niveau du site, telle qu'un
Si votre application n'est pas hébergée par CLI ou si vous souhaitez explicitement conserver vous-même la configuration complète de Nginx, vous pouvez également l'écrire à la main.
Cependant, pour NocoBase, le proxy inverse de production est généralement plus qu'un simple `proxy_pass`. En plus de transmettre les requêtes API à l'application backend, une configuration complète et utilisable doit généralement gérer le répertoire de téléchargement, les ressources statiques frontales, WebSocket, la route `.well-known` et la page de secours SPA.
Cependant, pour NocoBase, le proxy inverse de production est généralement plus qu'un simple `proxy_pass`. En plus de transmettre les requêtes API à l'application backend, une configuration complète et utilisable doit généralement gérer le répertoire de téléversement, les ressources statiques frontales, la route d'accès aux fichiers `/files/`, WebSocket, la route `.well-known` et les pages de secours de la SPA.
En prenant `test2` comme exemple, les fichiers et répertoires clés liés à Nginx incluent généralement :
@@ -138,6 +138,7 @@ En dautres termes, la configuration manuscrite doit généralement couvrir au
- `uploads` : exposez le répertoire de téléchargement via `alias`
- `dist` : exposez le répertoire du produit de build frontal via `alias`
- `well-known` : gérer les chemins de découverte liés à OAuth/OpenID
- `files` : transmettre les requêtes d'accès aux fichiers sous `/files/` à l'application backend
- `api` : transmettre la requête `/api/` à l'application backend
- `ws` : transmettre les requêtes WebSocket à l'application backend
- `spa` : fournit une entrée frontale et une solution de repli `try_files` pour `/` et `/v/`
@@ -180,6 +181,11 @@ server {
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /files/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /api/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
@@ -229,7 +235,15 @@ Une approche plus prudente est généralement la suivante :
2. Confirmez la structure de routage et le chemin réel en fonction des résultats générés.
3. Effectuez ensuite des ajustements manuels en fonction de votre nom de domaine, de votre mode d'exécution et du chemin de montage.
Il est généralement moins probable de manquer des détails liés aux WebSockets, aux ressources statiques, aux répertoires de téléchargement ou aux pages de secours SPA que d'écrire manuellement une configuration à partir de zéro.
Il est généralement moins probable de manquer des détails liés à `/files/`, aux WebSockets, aux ressources statiques, aux répertoires de téléversement ou aux pages de secours de la SPA que d'écrire une configuration à partir de zéro.
:::warning Attention
`/files/` est une route applicative qui doit passer par l'autorisation NocoBase. Ne la traitez pas comme un répertoire statique et ne la laissez pas atteindre le fallback de la SPA. Transmettez-la au backend NocoBase et placez la règle avant `location /` et les autres règles de fallback du front-end.
Si `APP_PUBLIC_PATH=/nocobase/` est configuré, transmettez également `/nocobase/files/`. Conservez la règle `/files/` à la racine pour assurer la compatibilité avec les URL de fichiers existantes.
:::
## Comment gérer HTTPS
+5
View File
@@ -59,6 +59,11 @@
"label": "Field Attachment",
"link": "/file-manager/field-attachment"
},
{
"type": "custom-link",
"label": "URL stabil",
"link": "/file-manager/stable-url"
},
{
"type": "custom-link",
"label": "File Preview",
+57
View File
@@ -0,0 +1,57 @@
---
pkg: '@nocobase/plugin-file-manager'
title: "URL stabil (URL proxy)"
description: "Menjelaskan format, izin, pengalihan, dan perilaku URL file stabil di NocoBase."
keywords: "URL stabil,URL proxy,URL permanen,akses file,pratinjau Office,NocoBase"
---
# URL stabil
File yang dikelola oleh storage engine NocoBase diakses melalui **URL stabil**. NocoBase memeriksa record file dan izin akses, lalu mengalihkan permintaan ke URL aktual yang dibuat oleh storage engine.
## Format
```text
/files/<app>/<dataSource>/<collection>/<id><extname>
```
Jika `APP_PUBLIC_PATH=/nocobase`, path dimulai dengan `/nocobase/files/`. ID dan ekstensi tidak dapat diubah setelah file dibuat, sehingga URL tetap stabil selama record masih ada.
| Penggunaan | URL | Perilaku |
|---|---|---|
| Membuka | `/files/.../42.pdf` | Memeriksa izin dan mengalihkan ke file |
| Pratinjau | `/files/.../42.png?preview=1` | Mengalihkan ke thumbnail atau URL pratinjau |
| Unduh | `/files/.../42.pdf?download=1` | Mengalihkan dengan mode unduh |
| Office | `/files/.../42.xlsx?temporaryAccessToken=...` | Akses sementara untuk Office Online Viewer |
## Perilaku di NocoBase
- Field attachment, file collection, dan [HTTP API](./http-api.md) mengembalikan URL stabil pada `url` dan `preview`
- Markdown menyimpan URL stabil dan mendukung S3, OSS, COS, serta S3 Pro privat
- Field URL attachment mempertahankan URL eksternal yang dimasukkan manual dan memakai URL stabil untuk upload yang dikelola NocoBase
- Pratinjau biasa memakai sesi login dan izin file NocoBase saat ini
- Form publik hanya memberi akses terbatas ke file yang diunggah dalam sesi form tersebut
## Pratinjau Office
Microsoft Office Online Viewer tidak dapat memakai cookie NocoBase milik pengguna. Saat pratinjau dibuka, NocoBase memeriksa izin terlebih dahulu lalu menerbitkan URL sementara yang terikat pada satu file. Masa berlaku default adalah 10 menit dan dapat diatur antara 5 sampai 10 menit melalui `TEMPORARY_FILE_ACCESS_EXPIRES_IN`.
Jangan simpan URL sementara ini ke field, Markdown, atau data bisnis, dan jangan gunakan sebagai tautan berbagi.
## Catatan penting
- Stabil tidak berarti publik; penerima tetap memerlukan izin
- Menghapus atau memindahkan record ke konteks lain akan membatalkan URL lama
- Respons berupa pengalihan `302` yang harus diikuti oleh klien
- Jangan menyimpan `302 Location` atau `temporaryAccessToken`
- Reverse proxy harus meneruskan rute `/files/` di bawah `APP_PUBLIC_PATH` ke NocoBase. Untuk deployment pada subpath, pertahankan juga rute kompatibilitas `/files/` di root. Konfigurasi yang dibuat oleh NocoBase CLI otomatis mencakup kedua rute tersebut
- Pada deployment ketika halaman mengakses API secara lintas origin (`API_BASE_URL` menunjuk ke origin lain), origin halaman harus ditambahkan ke `CORS_ORIGIN_WHITELIST`. Jika tidak, cookie login tidak akan pernah tersimpan dan stable URL akan mengembalikan `403` karena kredensial tidak ikut terkirim. Lihat [Variabel lingkungan](../get-started/installation/env.md#api_base_url)
- Gunakan `hostname` yang berbeda untuk setiap layanan NocoBase yang berdiri sendiri, bukan hanya membedakannya berdasarkan port. Cookie browser tidak diisolasi berdasarkan port; lihat [Deployment environment produksi](../get-started/deployment/production.md)
- Sub-app dalam deployment NocoBase yang sama dibedakan berdasarkan nama aplikasi dan tidak memerlukan hostname terpisah. Namun, layanan independen pada port lain tetap harus diisolasi dengan hostname jika memiliki aplikasi utama atau sub-app dengan nama yang sama
## Tautan terkait
- [HTTP API](./http-api.md) — Mengunggah dan mengambil file
- [Pratinjau file](./file-preview/index.md) — Format pratinjau yang didukung
- [Pratinjau Office](./file-preview/ms-office.md) — Mengatur Office Viewer
- [Storage engine](./storage/index.md) — Mengatur penyimpanan file
@@ -8,12 +8,34 @@ keywords: "Deployment Lingkungan Produksi,Deployment Produksi,Deployment Docker,
Saat men-deploy NocoBase di lingkungan produksi, karena perbedaan cara build pada sistem dan lingkungan yang berbeda, instalasi dependencies bisa menjadi rumit. Untuk mendapatkan pengalaman fitur yang lengkap, kami merekomendasikan menggunakan **Docker** untuk deployment. Jika lingkungan sistem tidak dapat menggunakan Docker, Anda juga dapat menggunakan **create-nocobase-app** untuk deployment.
:::warning
:::warning Perhatian
Tidak disarankan untuk langsung men-deploy source code di lingkungan produksi. Source code memiliki banyak dependencies, ukuran yang besar, dan kompilasi penuh memerlukan CPU dan memori yang tinggi. Jika benar-benar perlu menggunakan source code untuk deployment, disarankan untuk membangun image Docker kustom terlebih dahulu, kemudian melakukan deployment.
:::
:::warning Perhatian
Jika men-deploy beberapa layanan NocoBase yang berdiri sendiri, gunakan `hostname` yang berbeda untuk setiap layanan, misalnya subdomain yang berbeda. Jangan hanya membedakan layanan berdasarkan port seperti `https://example.com:13000` dan `https://example.com:14000`.
NocoBase menggunakan cookie untuk mempertahankan status login dan [izin akses file](../../file-manager/stable-url.md). Browser tidak mengisolasi cookie berdasarkan port, sehingga layanan pada port berbeda di bawah `hostname` yang sama dapat berbagi cookie dengan nama yang sama. Hal ini dapat menimpa status login atau menyebabkan kegagalan otorisasi pada pratinjau dan unduhan file.
Sub-app dalam deployment NocoBase yang sama tidak termasuk dalam pembatasan ini. Cookie login dibedakan berdasarkan nama aplikasi, sehingga aplikasi utama dan sub-app dengan nama berbeda dapat berbagi `hostname` yang sama.
Namun, layanan independen tetap harus diisolasi. Jika layanan NocoBase lain berjalan pada port berbeda di bawah `hostname` yang sama dan memiliki aplikasi utama atau sub-app dengan nama yang sama, cookie tetap dapat mengalami konflik.
Gunakan alamat seperti `app1.example.com` dan `app2.example.com`, lalu arahkan ke layanan NocoBase yang berbeda melalui Nginx atau Caddy.
:::
## Frontend terpisah / Akses API lintas origin
Sebaiknya halaman dan API tetap berada pada origin yang sama: gunakan reverse proxy di domain yang sama untuk meneruskan `${APP_PUBLIC_PATH}api/` dan `${APP_PUBLIC_PATH}files/` ke layanan NocoBase, lalu biarkan `API_BASE_URL` kosong.
Jika halaman memang harus mengakses API secara lintas origin (`API_BASE_URL` menunjuk ke origin lain), tambahkan origin halaman ke `CORS_ORIGIN_WHITELIST`. Jika tidak, browser akan mengabaikan `Set-Cookie` pada respons API, cookie login tidak akan tersimpan, dan pratinjau maupun unduhan melalui stable file URL akan gagal otorisasi.
Perhatikan juga bahwa cookie disimpan per `hostname`: jika halaman dan API menggunakan domain yang benar-benar berbeda, permintaan ke `/files/` dari domain halaman tidak akan membawa cookie login yang tersimpan di domain API. Deployment seperti ini sebaiknya diubah ke reverse proxy same-origin. Lihat [Variabel lingkungan](../installation/env.md#api_base_url).
## Alur Deployment
Deployment lingkungan produksi dapat merujuk ke langkah-langkah instalasi dan upgrade yang sudah ada.
@@ -94,6 +94,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` memungkinkan kontainer Caddy mengakses layanan `app` melalui jaringan Compose
- `./storage` harus dimount ke `app` dan `caddy` agar konfigurasi proxy, aset statis, dan file unggahan bisa dipakai bersama
- Kontainer `caddy` perlu menunggu sampai `nocobase.caddy` dibuat, lalu menautkannya ke `/etc/caddy/Caddyfile` dengan `ln -sf`
- Konfigurasi yang dibuat otomatis meneruskan rute `/files/` di bawah `APP_PUBLIC_PATH` dan rute `/files/` di root ke NocoBase untuk pratinjau dan unduhan file yang memerlukan autentikasi
- Ekspos hanya port kontainer Caddy ke host. Untuk pengujian, Anda bisa mulai dengan `13000:80`; di produksi, biasanya langsung ekspos port host `80` dan `443`, sementara layanan `app` tidak perlu membuka port ke host
## Jika menggunakan Caddy lokal di host
@@ -169,6 +170,8 @@ sudo systemctl reload caddy
Jika Caddy lokal Anda tidak menggunakan `/etc/caddy/Caddyfile`, ganti target link dengan path konfigurasi Anda sendiri. Biasanya lebih aman membiarkan `nocobase.caddy` tetap sebagai file masuk utama daripada menyalin isinya secara manual.
Jika Anda mengelola Caddy sendiri dan tidak menggunakan konfigurasi yang dibuat otomatis, pastikan `/files/*` serta rute terkait di bawah `APP_PUBLIC_PATH` diteruskan ke NocoBase sebelum rule fallback SPA. Lihat [Reverse proxy Caddy](../../nocobase-cli/production/reverse-proxy/caddy.md) untuk contoh lengkap.
## Tautan terkait
- [Instalasi Docker (Nginx bawaan)](./docker.mdx) — Mulai dari deployment satu kontainer
@@ -95,6 +95,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` memungkinkan kontainer Nginx mengakses layanan `app` melalui jaringan Compose
- `./storage` harus dimount ke `app` dan `nginx` agar konfigurasi proxy, aset statis, dan file unggahan bisa dipakai bersama
- Kontainer `nginx` perlu menunggu sampai `nocobase.conf` dibuat, lalu menautkannya ke `/etc/nginx/conf.d/default.conf` dengan `ln -sf`
- Konfigurasi yang dibuat otomatis meneruskan rute `/files/` di bawah `APP_PUBLIC_PATH` dan rute `/files/` di root ke NocoBase untuk pratinjau dan unduhan file yang memerlukan autentikasi
- Jika menggunakan kontainer Nginx eksternal, biarkan kontainer `nginx` menangani mapping port host. Untuk pengujian, Anda bisa mulai dengan `13000:80`; di produksi, biasanya langsung ekspos port host `80` dan `443`, sementara layanan `app` tidak perlu membuka port ke host
## Jika menggunakan Nginx lokal di host
@@ -170,6 +171,8 @@ sudo systemctl reload nginx
Jika Nginx lokal Anda tidak menggunakan direktori `conf.d`, ganti target link dengan path konfigurasi Anda sendiri. Biasanya lebih aman membiarkan `nocobase.conf` tetap sebagai file yang di-include dari konteks `http {}` daripada menyalin isinya secara manual.
Jika Anda mengelola Nginx sendiri dan tidak menggunakan konfigurasi yang dibuat otomatis, pastikan `/files/` serta rute terkait di bawah `APP_PUBLIC_PATH` diteruskan ke NocoBase sebelum rule fallback SPA. Lihat [Reverse proxy Nginx](../../nocobase-cli/production/reverse-proxy/nginx.md) untuk contoh lengkap.
## Tautan terkait
- [Instalasi Docker (Nginx bawaan)](./docker.mdx) — Mulai dari deployment satu kontainer
@@ -633,7 +633,7 @@ Jika Anda menggunakan image dengan Nginx bawaan, biasanya lebih baik tidak menge
Konfigurasi berikut mem-proxy permintaan domain ke `http://127.0.0.1:13000/`:
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # Ganti your_domain.com dengan domain Anda
@@ -664,6 +664,8 @@ server {
Jika Anda juga ingin mengaktifkan HTTPS, konfigurasikan `443` dan sertifikat di Nginx host. Kontainer NocoBase tidak perlu menangani sertifikat secara terpisah.
Blok `location /` pada konfigurasi root path ini juga meneruskan `/api/`, `/ws`, dan `/files/`. Jika Anda memisahkan aset statis dari rute aplikasi, pastikan `/files/` tetap diteruskan ke NocoBase dan tidak diperlakukan sebagai direktori statis.
### Deployment subpath
Jika Anda ingin men-deploy aplikasi di subpath, misalnya `https://your_domain.com/nocobase/`, konfigurasikan dulu variabel lingkungan `APP_PUBLIC_PATH`:
@@ -680,7 +682,7 @@ Pertahankan `/` di awal dan akhir path. Setelah dikonfigurasi, URL aplikasi menj
Lalu konfigurasikan Nginx host dengan proxy subpath yang sama:
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # Ganti your_domain.com dengan domain Anda
@@ -706,10 +708,32 @@ server {
send_timeout 600;
proxy_buffering off;
}
# Pertahankan kompatibilitas dengan URL akses file di root.
location ^~ /files/ {
proxy_pass http://127.0.0.1:13000;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $upstream_x_forwarded_proto;
proxy_set_header Host $final_host;
proxy_set_header Referer $http_referer;
proxy_set_header User-Agent $http_user_agent;
add_header Cache-Control "no-cache, no-store" always;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
}
}
```
Poin utamanya adalah `APP_PUBLIC_PATH` dan path di `proxy_pass` harus konsisten. Jika salah satu sisi tidak menyertakan `/nocobase/`, aset statis dan routing biasanya tidak akan berjalan dengan benar.
Perhatikan hal berikut:
- `APP_PUBLIC_PATH` dan path di `proxy_pass` harus konsisten. Jika salah satu sisi tidak menyertakan `/nocobase/`, aset statis dan routing biasanya tidak akan berjalan dengan benar
- `/nocobase/files/` diteruskan oleh `location /nocobase/`; rute kompatibilitas `/files/` di root harus diteruskan ke NocoBase secara terpisah
### Opsi lain
@@ -92,6 +92,39 @@ API_BASE_PATH=/api/
### API_BASE_URL
URL dasar yang digunakan frontend untuk mengakses API NocoBase. Secara default kosong, yang berarti `${APP_PUBLIC_PATH}api/` pada origin yang sama akan digunakan.
```bash
API_BASE_URL=
```
Hanya isi dengan alamat API lengkap ketika halaman dan layanan API berada pada origin yang berbeda (protokol, domain, atau port berbeda):
```bash
API_BASE_URL=https://api.example.com/api/
```
:::warning{title="Deployment lintas origin"}
NocoBase menggunakan cookie untuk mempertahankan status login dan mengotorisasi akses ke [stable file URL](../../file-manager/stable-url.md). Ketika `API_BASE_URL` menunjuk ke origin yang berbeda dari halaman:
- Origin halaman harus ditambahkan ke [`CORS_ORIGIN_WHITELIST`](#cors_origin_whitelist). Jika tidak, browser akan mengabaikan `Set-Cookie` pada respons API, cookie login tidak akan tersimpan, dan fitur yang bergantung pada cookie seperti pratinjau serta unduhan file akan gagal dengan `403`.
- Cookie disimpan per `hostname`. Jika halaman dan API menggunakan domain yang sepenuhnya berbeda, request ke stable URL di bawah `/files/` dari domain halaman tidak akan mengirim cookie login yang tersimpan di domain API, sehingga akses file tetap gagal.
Sebaiknya sajikan halaman dan API dari origin yang sama melalui reverse proxy dan biarkan `API_BASE_URL` kosong.
:::
### CORS_ORIGIN_WHITELIST
Daftar whitelist origin yang diizinkan mengakses API secara lintas origin dengan kredensial (cookie). Pisahkan beberapa origin dengan koma. Secara default kosong.
```bash
CORS_ORIGIN_WHITELIST=https://www.example.com,https://admin.example.com
```
- Jika tidak dikonfigurasi, hanya request dari origin yang sama yang dianggap tepercaya; request lintas origin tetap bisa memanggil API secara anonim, tetapi browser tidak diizinkan membaca atau menulis cookie untuk request tersebut.
- Jika dikonfigurasi, origin dalam whitelist akan menerima `Access-Control-Allow-Origin` yang mencerminkan origin secara tepat dan `Access-Control-Allow-Credentials: true`, sehingga browser dapat mengirim dan menyimpan cookie login pada request lintas origin.
- API sign-in memvalidasi `Origin` dan `Referer` dari request; request sign-in lintas origin dari origin di luar whitelist akan ditolak dengan `403`.
### CLUSTER_MODE
> `v1.6.0+`
@@ -69,6 +69,16 @@ Jika Anda terjebak di sini "Mengapa Anda memerlukan `nb app autostart`", lanjutk
- Jika Anda akan terhubung ke proxy terbalik, `appPort` telah disimpan di env
- Jika Anda siap membukanya secara resmi ke dunia luar, Anda sudah merencanakan nama domain, port masuk, dan solusi HTTPS.
:::warning Perhatian
Gunakan `hostname` yang berbeda, seperti subdomain terpisah, untuk setiap layanan NocoBase yang independen. Jangan hanya membedakan layanan berdasarkan port. Cookie browser tidak diisolasi berdasarkan port, sehingga layanan di bawah `hostname` yang sama dapat menimpa status login dan memengaruhi otorisasi [URL stabil](../../file-manager/stable-url.md).
Sub-app dalam deployment NocoBase yang sama dibedakan berdasarkan nama aplikasi dan tidak memerlukan hostname terpisah. Namun, jika layanan NocoBase independen lain berjalan pada port berbeda di bawah `hostname` yang sama dan memiliki aplikasi utama atau sub-app dengan nama yang sama, cookie tetap dapat mengalami konflik.
Misalnya, gunakan `app1.example.com` dan `app2.example.com`, bukan `example.com:13000` dan `example.com:14000`.
:::
Jika Anda belum menyelesaikan instalasi CLI atau inisialisasi env, kembali ke [Instalasi menggunakan CLI (disarankan)](../installation/cli.md).
Jika perintah meminta env hilang `appPort`, jalankan dulu [`nb env update`](../../api/cli/env/update.md) untuk mengisinya.
@@ -124,7 +124,7 @@ Jika Anda ingin mengimbangi konfigurasi tingkat situs Caddy, seperti header tamb
Jika aplikasi Anda tidak dihosting CLI, atau Anda secara eksplisit ingin mempertahankan sendiri konfigurasi Caddy yang lengkap, Anda juga dapat menulisnya dengan tangan.
Namun, untuk NocoBase, entri lingkungan produksi biasanya bukan sekadar `reverse_proxy`. Selain meneruskan permintaan API ke aplikasi backend, konfigurasi Caddy yang lengkap dan berfungsi biasanya juga perlu menangani direktori unggahan, sumber daya statis front-end, perutean `.well-known`, WebSocket, dan halaman fallback SPA.
Namun, untuk NocoBase, entry environment produksi biasanya tidak hanya berupa `reverse_proxy` sederhana. Selain meneruskan permintaan API ke aplikasi backend, konfigurasi Caddy yang lengkap juga perlu menangani direktori unggahan, aset statis front-end, rute akses file `/files/`, routing `.well-known`, WebSocket, dan halaman fallback SPA.
Mengambil `test2` sebagai contoh, direktori utama yang terkait dengan Caddy biasanya mencakup:
@@ -139,6 +139,7 @@ Dengan kata lain, konfigurasi tulisan tangan biasanya perlu mencakup setidaknya
- `dist`: Mengekspos direktori produk build front-end
- `oauth well-known`: Menangani jalur penemuan OAuth
- `openid well-known`: Menangani jalur penemuan OpenID
- `files`: meneruskan permintaan akses file di bawah `/files/` ke aplikasi backend
- `api`: meneruskan permintaan `/api/` ke aplikasi backend
- `ws`: meneruskan permintaan WebSocket ke aplikasi backend
- `spa v2`: Menyediakan entri front-end dan halaman kembali untuk `/v/`
@@ -187,6 +188,10 @@ c.local.nocobase.com {
reverse_proxy host.docker.internal:56575
}
handle /files/* {
reverse_proxy host.docker.internal:56575
}
handle /api/* {
reverse_proxy host.docker.internal:56575
}
@@ -249,7 +254,15 @@ Pendekatan yang lebih bijaksana biasanya adalah:
2. Konfirmasikan struktur perutean dan jalur sebenarnya berdasarkan hasil yang dihasilkan.
3. Kemudian lakukan penyesuaian manual sesuai dengan nama domain Anda, mode pengoperasian, dan jalur pemasangan.
Hal ini biasanya lebih kecil kemungkinannya untuk melewatkan detail terkait WebSockets, sumber daya statis, direktori unggahan, rute `.well-known`, atau halaman cadangan SPA dibandingkan dengan menulis konfigurasi dari awal dengan tangan.
Cara ini biasanya lebih kecil kemungkinannya melewatkan detail terkait `/files/`, WebSocket, aset statis, direktori unggahan, route `.well-known`, atau halaman fallback SPA dibanding menulis konfigurasi dari nol.
:::warning Perhatian
`/files/` adalah rute aplikasi yang harus melalui otorisasi NocoBase. Jangan menanganinya sebagai direktori statis atau membiarkannya masuk ke fallback SPA. Teruskan rute ini ke backend NocoBase dan letakkan rule sebelum `handle_path /*` serta rule fallback frontend lainnya.
Jika `APP_PUBLIC_PATH=/nocobase/` dikonfigurasi, teruskan juga `/nocobase/files/*`. Pertahankan rule `/files/*` di root untuk kompatibilitas dengan URL file yang sudah ada.
:::
## Periksa dan muat ulang konfigurasi
@@ -9,7 +9,7 @@ keywords: "NocoBase,nb proxy nginx,nb proxy caddy, reverse proxy, Nginx, Caddy,
Artikel ini hanya berlaku untuk aplikasi yang diinstal menggunakan `nb init`.
Di NocoBase, proksi terbalik lingkungan produksi melakukan lebih dari sekadar meneruskan permintaan ke proses aplikasi. Seringkali detail WebSockets, subjalur, sumber daya statis front-end, direktori unggahan, dan halaman cadangan SPA juga ditangani secara bersamaan.
Di NocoBase, reverse proxy lingkungan produksi tidak hanya meneruskan permintaan ke proses aplikasi. Konfigurasi juga perlu menangani WebSocket, subpath, aset statis front-end, direktori unggahan, rute akses file `/files/`, dan halaman fallback SPA.
Fungsi `nb proxy` adalah untuk mengumpulkan detail yang mudah terlewatkan ini ke dalam kumpulan entri perintah yang stabil.
@@ -122,7 +122,7 @@ Jika Anda ingin menambahkan konfigurasi Nginx tingkat situs, seperti batasan saa
Jika aplikasi Anda tidak dihosting CLI, atau Anda secara eksplisit ingin mempertahankan sendiri konfigurasi Nginx yang lengkap, Anda juga dapat menulisnya dengan tangan.
Namun, untuk NocoBase, proksi balik produksi biasanya lebih dari sekadar `proxy_pass`. Selain meneruskan permintaan API ke aplikasi backend, konfigurasi yang lengkap dan dapat digunakan biasanya perlu menangani direktori unggahan, sumber daya statis front-end, WebSocket, rute `.well-known`, dan halaman fallback SPA.
Namun, untuk NocoBase, reverse proxy produksi biasanya lebih dari sekadar `proxy_pass`. Selain meneruskan permintaan API ke aplikasi backend, konfigurasi yang lengkap juga perlu menangani direktori unggahan, aset statis front-end, rute akses file `/files/`, WebSocket, route `.well-known`, serta halaman fallback SPA.
Mengambil `test2` sebagai contoh, file dan direktori utama yang terkait dengan Nginx biasanya mencakup:
@@ -138,6 +138,7 @@ Dengan kata lain, konfigurasi tulisan tangan biasanya perlu mencakup setidaknya
- `uploads`: Menampilkan direktori unggahan melalui `alias`
- `dist`: Mengekspos direktori produk build front-end melalui `alias`
- `well-known`: Menangani jalur penemuan terkait OAuth/OpenID
- `files`: meneruskan permintaan akses file di bawah `/files/` ke aplikasi backend
- `api`: meneruskan permintaan `/api/` ke aplikasi backend
- `ws`: meneruskan permintaan WebSocket ke aplikasi backend
- `spa`: Menyediakan entri front-end dan `try_files` cadangan untuk `/` dan `/v/`
@@ -180,6 +181,11 @@ server {
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /files/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /api/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
@@ -229,7 +235,15 @@ Pendekatan yang lebih bijaksana biasanya adalah:
2. Konfirmasikan struktur perutean dan jalur sebenarnya berdasarkan hasil yang dihasilkan.
3. Kemudian lakukan penyesuaian manual sesuai dengan nama domain Anda, mode pengoperasian, dan jalur pemasangan.
Hal ini biasanya lebih kecil kemungkinannya untuk melewatkan detail terkait WebSockets, sumber daya statis, direktori unggahan, atau halaman cadangan SPA dibandingkan dengan menulis konfigurasi dari awal dengan tangan.
Cara ini biasanya lebih kecil kemungkinannya melewatkan detail terkait `/files/`, WebSocket, aset statis, direktori unggahan, atau halaman fallback SPA dibanding menulis konfigurasi dari nol.
:::warning Perhatian
`/files/` adalah rute aplikasi yang harus melalui otorisasi NocoBase. Jangan menanganinya sebagai direktori statis atau membiarkannya masuk ke fallback SPA. Teruskan rute ini ke backend NocoBase dan letakkan rule sebelum `location /` serta rule fallback frontend lainnya.
Jika `APP_PUBLIC_PATH=/nocobase/` dikonfigurasi, teruskan juga `/nocobase/files/`. Pertahankan rule `/files/` di root untuk kompatibilitas dengan URL file yang sudah ada.
:::
## Cara menangani HTTPS
+5
View File
@@ -59,6 +59,11 @@
"label": "添付フィールド",
"link": "/file-manager/field-attachment"
},
{
"type": "custom-link",
"label": "安定 URL",
"link": "/file-manager/stable-url"
},
{
"type": "custom-link",
"label": "ファイルプレビュー",
+57
View File
@@ -0,0 +1,57 @@
---
pkg: '@nocobase/plugin-file-manager'
title: "安定 URL(プロキシ URL"
description: "NocoBase の安定したファイル URL の形式、アクセス権限、リダイレクト、Office プレビューでの動作を説明します。"
keywords: "安定 URL,プロキシ URL,永久 URL,ファイルアクセス,Office プレビュー,NocoBase"
---
# 安定 URL
NocoBase のストレージエンジンで管理されるファイルは、**安定 URL** を通してアクセスされます。NocoBase がファイルレコードと権限を確認した後、ストレージエンジンが生成した実際の URL へリダイレクトします。
## URL 形式
```text
/files/<app>/<dataSource>/<collection>/<id><extname>
```
`APP_PUBLIC_PATH=/nocobase` の場合は `/nocobase/files/` から始まります。ファイル作成後は ID と拡張子を変更できないため、レコードが存在する間は URL が安定します。
| 用途 | URL | 動作 |
|---|---|---|
| 表示 | `/files/.../42.pdf` | 権限確認後に実ファイルへリダイレクト |
| プレビュー | `/files/.../42.png?preview=1` | プレビューまたはサムネイルへリダイレクト |
| ダウンロード | `/files/.../42.pdf?download=1` | ダウンロード用 URL へリダイレクト |
| Office | `/files/.../42.xlsx?temporaryAccessToken=...` | Office Viewer が短時間だけ取得できる URL |
## 各機能での動作
- 添付フィールド、ファイルテーブル、[HTTP API](./http-api.md) は `url``preview` に安定 URL を返します
- Markdown にアップロードしたファイルも安定 URL を保存し、非公開の S3、OSS、COS、S3 Pro を利用できます
- 添付 URL フィールドでアップロードした管理対象ファイルは安定 URL を保存し、手入力した外部 URL はそのまま保持します
- 通常の画像、PDF、音声、動画、テキストプレビューは現在の NocoBase ログイン状態とファイル閲覧権限を使用します
- 公開フォームでは、同じ公開フォームセッションでアップロードしたファイルだけに限定アクセスできます
## Office プレビュー
Microsoft Office Online Viewer はユーザーの NocoBase cookie を利用できません。Office プレビューを開くと、NocoBase は先に閲覧権限を確認し、そのファイル専用の短期 URL を発行します。既定の有効期間は 10 分で、`TEMPORARY_FILE_ACCESS_EXPIRES_IN` により 5〜10 分に設定できます。
一時 URL を添付フィールド、Markdown、業務データに保存したり、共有リンクとして使用したりしないでください。
## 注意事項
- 安定 URL は公開 URL ではなく、閲覧者にはログインまたは anonymous 権限が必要です
- ファイルレコードを削除した場合や、アプリ、データソース、ファイルテーブルが変わった場合、元の URL は無効になります
- 応答は `302` です。CLI クライアントはリダイレクトを追跡する必要があります
- `302 Location``temporaryAccessToken` を永続化しないでください
- リバースプロキシは `APP_PUBLIC_PATH` 配下の `/files/` を NocoBase に転送する必要があります。サブパスにデプロイする場合は、ルートの `/files/` 互換ルートも残してください。NocoBase CLI が生成する設定には両方のルールが自動的に含まれます
- ページが API にクロスオリジンでアクセスする構成(`API_BASE_URL` が別オリジンを指す場合)では、ページのオリジンを `CORS_ORIGIN_WHITELIST` に追加する必要があります。そうしないとログイン cookie が保存されず、stable URL は認証情報不足で `403` を返します。詳しくは[環境変数](../get-started/installation/env.md#api_base_url)を参照してください
- 独立した複数の NocoBase サービスをデプロイする場合は、ポートだけで区別せず、それぞれに異なる `hostname` を使用してください。ブラウザーの cookie はポートでは分離されません。詳細は[本番環境へのデプロイ](../get-started/deployment/production.md)を参照してください
- 同じ NocoBase デプロイ環境内のサブアプリはアプリ名で区別されるため、個別の hostname は必要ありません。ただし、別ポート上の独立したサービスに同名のメインアプリまたはサブアプリがある場合は、引き続き異なる hostname で分離する必要があります
## 関連リンク
- [HTTP API](./http-api.md) — API でファイルをアップロードする
- [ファイルプレビュー](./file-preview/index.md) — 対応するプレビュー形式を確認する
- [Office ファイルプレビュー](./file-preview/ms-office.md) — Office Viewer を設定する
- [ストレージエンジン](./storage/index.md) — ファイルストレージを設定する
@@ -2,12 +2,34 @@
本番環境でNocoBaseをデプロイする際、システムや環境によってビルド方法が異なるため、依存関係のインストールが煩雑になることがあります。すべての機能を完全にご利用いただくために、**Docker** を使用したデプロイを推奨します。お使いのシステム環境でDockerが使用できない場合は、**create-nocobase-app** を使用してデプロイすることも可能です。
:::warning
:::warning 注意
本番環境でソースコードから直接デプロイすることは推奨されません。ソースコードは依存関係が多く、サイズが大きいため、フルコンパイルには高いCPUとメモリが要求されます。どうしてもソースコードからデプロイする必要がある場合は、まずカスタムDockerイメージをビルドしてからデプロイすることをお勧めします。
:::
:::warning 注意
独立した複数の NocoBase サービスをデプロイする場合は、サービスごとに異なる `hostname`(別々のサブドメインなど)を使用してください。`https://example.com:13000``https://example.com:14000` のように、ポートだけでサービスを区別しないでください。
NocoBase は、ログイン状態と[ファイルアクセス権限](../../file-manager/stable-url.md)を維持するために cookie を使用します。ブラウザーの cookie はポートでは分離されないため、同じ `hostname` の異なるポート上にあるサービスが同名の cookie を共有することがあります。その結果、ログイン状態が上書きされたり、ファイルのプレビューやダウンロードの認証に失敗したりする可能性があります。
同じ NocoBase デプロイ環境内のサブアプリは、この制限の対象外です。ログイン cookie はアプリ名で区別されるため、メインアプリと名前の異なるサブアプリは同じ `hostname` を共有できます。
ただし、独立したサービス間の分離は引き続き必要です。同じ `hostname` の別ポートで別の NocoBase サービスを実行し、その中に同名のメインアプリまたはサブアプリがある場合、cookie が競合する可能性があります。
`app1.example.com``app2.example.com` のようなアドレスを使用し、Nginx または Caddy でそれぞれの NocoBase サービスに振り分けてください。
:::
## フロントエンド分離 / クロスオリジン API アクセス
ページと API は同一オリジンに保つことを推奨します。同一ドメイン配下のリバースプロキシで `${APP_PUBLIC_PATH}api/``${APP_PUBLIC_PATH}files/` を NocoBase サービスへ転送し、`API_BASE_URL` は空のままにしてください。
ページが API にクロスオリジンでアクセスする必要がある場合(`API_BASE_URL` が別オリジンを指す場合)、ページのオリジンを `CORS_ORIGIN_WHITELIST` に追加してください。そうしないと、ブラウザーは API レスポンス内の `Set-Cookie` を無視し、ログイン cookie が保存されず、stable file URL によるプレビューやダウンロードの認可に失敗します。
あわせて、cookie は `hostname` ごとに保存される点にも注意してください。ページと API が完全に異なるドメインを使っている場合、ページ側ドメインから `/files/` へ送るリクエストには API ドメインに保存されたログイン cookie が含まれません。この種の構成は、同一オリジンのリバースプロキシへ切り替えるべきです。詳しくは[環境変数](../installation/env.md#api_base_url)を参照してください。
## デプロイプロセス
本番環境へのデプロイは、既存のインストールおよびアップグレード手順を参照してください。
@@ -39,4 +61,4 @@
インストール方法に応じて、以下のコマンドを使用してNocoBaseプロセスを管理できます。
- [docker compose](./common-commands/docker-compose.md)
- [pm2](./common-commands/pm2.md)
- [pm2](./common-commands/pm2.md)
@@ -95,6 +95,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` により、Caddy コンテナは Compose ネットワーク経由で `app` サービスへ接続します
- `./storage` は `app` と `caddy` の両方にマウントし、プロキシ設定、静的アセット、アップロードファイルを共有できるようにします
- `caddy` コンテナは `nocobase.caddy` が生成されるまで待機し、その後 `ln -sf` で `/etc/caddy/Caddyfile` にリンクしてから起動します
- 自動生成される設定は、`APP_PUBLIC_PATH` 配下の `/files/` とルートの `/files/` の両方を NocoBase に転送し、認証付きのファイルプレビューとダウンロードを処理します
- ホストへ公開するのは Caddy コンテナのポートだけで十分です。テスト時は `13000:80` から始められますが、本番環境では通常ホストの `80` と `443` を直接公開し、`app` サービスはホストへポートを公開する必要はありません
## ホストにインストールした Caddy を使う場合
@@ -170,6 +171,8 @@ sudo systemctl reload caddy
ホスト側の Caddy が `/etc/caddy/Caddyfile` を使っていない場合は、リンク先を自分の設定パスに置き換えてください。通常は `nocobase.caddy` を主入口ファイルとしてそのまま使うほうが安全で、内容を手で分解してコピーするのはおすすめしません。
自動生成された設定を使わずに Caddy を自分で管理する場合は、`/files/*` と `APP_PUBLIC_PATH` 配下の対応するルートを、SPA フォールバックルールより前で NocoBase に転送してください。完全な例は [Caddy リバースプロキシ](../../nocobase-cli/production/reverse-proxy/caddy.md)を参照してください。
## 関連リンク
- [Docker でのインストール(内蔵 Nginx](./docker.mdx) — まずは単一コンテナ構成から始める
@@ -96,6 +96,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` により、Nginx コンテナは Compose ネットワーク経由で `app` サービスへ接続します
- `./storage` は `app` と `nginx` の両方にマウントし、プロキシ設定、静的アセット、アップロードファイルを共有できるようにします
- `nginx` コンテナは `nocobase.conf` が生成されるまで待機し、その後 `ln -sf` で `/etc/nginx/conf.d/default.conf` にリンクしてから起動します
- 自動生成される設定は、`APP_PUBLIC_PATH` 配下の `/files/` とルートの `/files/` の両方を NocoBase に転送し、認証付きのファイルプレビューとダウンロードを処理します
- 外部 Nginx コンテナを使う場合は、ホスト側のポートマッピングを `nginx` コンテナで処理します。テスト時は `13000:80` から始められますが、本番環境では通常ホストの `80` と `443` を直接公開し、`app` サービスはホストへポートを公開する必要はありません
## ホストにインストールした Nginx を使う場合
@@ -171,6 +172,8 @@ sudo systemctl reload nginx
ホスト側の Nginx が `conf.d` ディレクトリを使っていない場合は、リンク先を自分の設定パスに置き換えてください。通常は `nocobase.conf` を `http {}` から include するファイルとしてそのまま使うほうが安全で、内容を手で分解してコピーするのはおすすめしません。
自動生成された設定を使わずに Nginx を自分で管理する場合は、`/files/` と `APP_PUBLIC_PATH` 配下の対応するルートを、SPA フォールバックルールより前で NocoBase に転送してください。完全な例は [Nginx リバースプロキシ](../../nocobase-cli/production/reverse-proxy/nginx.md)を参照してください。
## 関連リンク
- [Docker でのインストール(内蔵 Nginx](./docker.mdx) — まずは単一コンテナ構成から始める
@@ -627,7 +627,7 @@ app-postgres-app-1 | 🚀 NocoBase server running at: http://localhost:13000/
次の設定では、ドメインへのリクエストを `http://127.0.0.1:13000/` にプロキシします。
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # your_domain.com を自分のドメインに置き換えてください
@@ -658,6 +658,8 @@ server {
HTTPS も有効にする場合は、ホスト側の Nginx で `443` と証明書を設定してください。NocoBase コンテナ側で証明書を個別に処理する必要はありません。
このルートパス構成の `location /` は、`/api/`、`/ws`、`/files/` もプロキシします。静的リソースとアプリケーションルートを分離する場合も、`/files/` を静的ディレクトリとして扱わず、NocoBase に転送してください。
### サブパスへのデプロイ
アプリを `https://your_domain.com/nocobase/` のようなサブパスにデプロイする場合は、先に `APP_PUBLIC_PATH` 環境変数を設定します。
@@ -674,7 +676,7 @@ services:
続いて、ホスト側の Nginx でも同じサブパスでプロキシを設定します。
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # your_domain.com を自分のドメインに置き換えてください
@@ -700,10 +702,32 @@ server {
send_timeout 600;
proxy_buffering off;
}
# ルート形式のファイルアクセス URL との互換性を維持します。
location ^~ /files/ {
proxy_pass http://127.0.0.1:13000;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $upstream_x_forwarded_proto;
proxy_set_header Host $final_host;
proxy_set_header Referer $http_referer;
proxy_set_header User-Agent $http_user_agent;
add_header Cache-Control "no-cache, no-store" always;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
}
}
```
重要なのは、`APP_PUBLIC_PATH` と `proxy_pass` のパスを一致させることです。どちらかで `/nocobase/` が抜けると、静的アセットやルーティングが正しく動かないことがあります
次の点に注意してください
- `APP_PUBLIC_PATH` と `proxy_pass` のパスを一致させます。どちらかで `/nocobase/` が抜けると、静的アセットやルーティングが正しく動かないことがあります
- `/nocobase/files/` は `location /nocobase/` で転送されます。互換用のルートパス `/files/` は別途 NocoBase に転送する必要があります
### その他の方法
@@ -86,6 +86,39 @@ API_BASE_PATH=/api/
### API_BASE_URL
フロントエンドが NocoBase API にアクセスするためのベース URL です。デフォルトは空で、その場合は同一オリジンの `${APP_PUBLIC_PATH}api/` を使用します。
```bash
API_BASE_URL=
```
ページと API サービスのオリジンが異なる場合(プロトコル、ドメイン、またはポートのいずれかが異なる場合)にのみ、完全な API アドレスを設定してください。
```bash
API_BASE_URL=https://api.example.com/api/
```
:::warning{title="クロスオリジン構成の注意"}
NocoBase は、ログイン状態の維持と [stable file URL](../../file-manager/stable-url.md) へのアクセス認可に cookie を使用します。`API_BASE_URL` がページとは別オリジンを指す場合:
- ページのオリジンを [`CORS_ORIGIN_WHITELIST`](#cors_origin_whitelist) に追加する必要があります。そうしないと、ブラウザーは API レスポンス内の `Set-Cookie` を無視し、ログイン cookie が保存されず、ファイルのプレビューやダウンロードなど cookie に依存する機能が `403` で失敗します。
- cookie は `hostname` ごとに保存されます。ページと API が完全に異なるドメインを使っている場合、ページ側ドメインから `/files/` の stable URL に送るリクエストには API ドメインに保存されたログイン cookie が含まれず、ファイルアクセスは引き続き失敗します。
そのため、リバースプロキシを使ってページと API を同一オリジンで配信し、`API_BASE_URL` は空のままにしておくことを推奨します。
:::
### CORS_ORIGIN_WHITELIST
資格情報(cookie)付きで API にクロスオリジンアクセスできるオリジンのホワイトリストです。複数のオリジンはカンマ区切りで指定します。デフォルトは空です。
```bash
CORS_ORIGIN_WHITELIST=https://www.example.com,https://admin.example.com
```
- 未設定の場合、信頼されるのは API と同一オリジンのリクエストだけです。クロスオリジンのリクエストでも匿名で API を呼び出すことはできますが、ブラウザーはそれらに対して cookie の読み書きを許可しません。
- 設定すると、ホワイトリスト内のオリジンには正確に反映された `Access-Control-Allow-Origin``Access-Control-Allow-Credentials: true` が返され、ブラウザーがクロスオリジンリクエストでログイン cookie を送信、保存できるようになります。
- サインイン API はリクエストの `Origin` / `Referer` を検証します。ホワイトリスト外のオリジンからのクロスオリジンサインインリクエストは `403` で拒否されます。
### CLUSTER_MODE
> `v1.6.0+`
@@ -69,6 +69,16 @@ nb app autostart run
- リバースプロキシに接続する場合は、`appPort`がenvに保存されています
- 正式に外部に公開する準備ができている場合は、ドメイン名、入口ポート、HTTPS ソリューションをすでに計画しています。
:::warning 注意
独立した NocoBase サービスごとに、別のサブドメインなど異なる `hostname` を使用してください。ポートだけでサービスを区別しないでください。ブラウザーの cookie はポートでは分離されないため、同じ `hostname` のサービスがログイン状態を上書きし、[安定 URL](../../file-manager/stable-url.md) の認証に影響する可能性があります。
同じ NocoBase デプロイ環境内のサブアプリはアプリ名で区別されるため、個別の hostname は必要ありません。ただし、同じ `hostname` の別ポートで独立した NocoBase サービスを実行し、その中に同名のメインアプリまたはサブアプリがある場合、cookie が競合する可能性があります。
たとえば、`example.com:13000``example.com:14000` ではなく、`app1.example.com``app2.example.com` を使用してください。
:::
CLI のインストールまたは環境の初期化が完了していない場合は、[CLI を使用したインストール (推奨)](../installation/cli.md) に戻ります。
env が `appPort` がないというコマンド プロンプトが表示された場合は、まず [`nb env update`](../../api/cli/env/update.md) を実行してそれを入力します。
@@ -124,7 +124,7 @@ nb proxy caddy reload
アプリケーションが CLI でホストされていない場合、または完全な Caddy 構成を自分で明示的に保守したい場合は、手動で作成することもできます。
ただし、NocoBase の場合、運用環境エントリは通常、単なる `reverse_proxy` ではありません。 API リクエストをバックエンド アプリケーションに転送することに加えて、完全で機能する Caddy 構成では通常、アップロード ディレクトリ、フロントエンド静的リソース、`.well-known` ルーティング、WebSocket、および SPA フォールバック ページも処理する必要があります。
ただし、NocoBase の本番環境エントリは、単純な `reverse_proxy` だけではありません。API リクエストの転送に加えて、アップロードディレクトリ、フロントエンド静的リソース、ファイルアクセスルート `/files/``.well-known` ルーティング、WebSocket、SPA フォールバックページも処理する必要があります。
`test2` を例に挙げると、通常、Caddy に関連する主要なディレクトリには次のものが含まれます。
@@ -139,6 +139,7 @@ nb proxy caddy reload
- `dist`: フロントエンド ビルド製品ディレクトリを公開します
- `oauth well-known`: OAuth 検出パスの処理
- `openid well-known`: OpenID 検出パスの処理
- `files`: `/files/` 配下のファイルアクセスリクエストをバックエンドアプリケーションへ転送します
- `api`: `/api/` リクエストをバックエンド アプリケーションに転送します
- `ws`: WebSocket リクエストをバックエンド アプリケーションに転送します。
- `spa v2`: `/v/` のフロントエンドのエントリとリターン ページを提供します
@@ -187,6 +188,10 @@ c.local.nocobase.com {
reverse_proxy host.docker.internal:56575
}
handle /files/* {
reverse_proxy host.docker.internal:56575
}
handle /api/* {
reverse_proxy host.docker.internal:56575
}
@@ -249,7 +254,15 @@ NB_CLI_ROOT/test2/storage/uploads
2. 生成された結果に基づいて、ルーティング構造と実際のパスを確認します。
3. 次に、ドメイン名、実行モード、マウント パスに従って手動で調整します。
通常、この方法では、構成を最初から手書きするよりも、WebSocket、静的リソース、アップロード ディレクトリ、`.well-known` ルート、または SPA フォールバック ページに関連する詳細を見逃す可能性が低くなります。
通常、この方法では、構成を最初から手書きするよりも、`/files/`WebSocket、静的リソース、アップロードディレクトリ、`.well-known` ルート、SPA フォールバックページに関連する詳細を見逃しにくくなります。
:::warning 注意
`/files/` は NocoBase の認証を通す必要があるアプリケーションルートです。静的ディレクトリとして処理したり、SPA フォールバックへ流したりしないでください。NocoBase バックエンドへ転送し、`handle_path /*` などのフロントエンドフォールバックルールより前に配置します。
`APP_PUBLIC_PATH=/nocobase/` を設定している場合は、`/nocobase/files/*` も転送してください。既存のファイル URL との互換性のため、ルートの `/files/*` ルールも残します。
:::
## 設定を確認してリロードする
@@ -9,7 +9,7 @@ keywords: "NocoBase、nb プロキシ nginx、nb プロキシ キャディ、リ
この記事は、`nb init` を使用してインストールされたアプリケーションにのみ適用されます。
NocoBase では、運用環境リバース プロキシは、単にリクエストをアプリケーション プロセス転送するだけではありません。多くの場合、WebSocket、サブパス、フロントエンド静的リソース、アップロード ディレクトリ、および SPA フォールバック ページの詳細も同時に処理されます。
NocoBase の本番環境リバースプロキシは、リクエストをアプリケーションプロセス転送するだけではありません。WebSocket、サブパス、フロントエンド静的リソース、アップロードディレクトリ、ファイルアクセスルート `/files/`SPA フォールバックページも処理する必要があります。
`nb proxy` の機能は、これらの見逃しやすい詳細を安定したコマンド エントリのセットに収集することです。
@@ -122,7 +122,7 @@ nb proxy nginx reload
アプリケーションが CLI でホストされていない場合、または完全な Nginx 構成を自分で明示的に保守したい場合は、手動で記述することもできます。
ただし、NocoBase の場合、実稼働リバース プロキシは通常、単純な `proxy_pass` 以上のものです。 API リクエストをバックエンド アプリケーションに転送することに加えて、完全で使用可能な構成では、通常、アップロード ディレクトリ、フロントエンド静的リソース、WebSocket、`.well-known` ルート、および SPA フォールバック ページ処理する必要があります。
ただし、NocoBase の本番環境リバースプロキシは、単純な `proxy_pass` だけではありません。API リクエストの転送に加えて、アップロードディレクトリ、フロントエンド静的リソース、ファイルアクセスルート `/files/`WebSocket、`.well-known` ルート、SPA フォールバックページ処理する必要があります。
`test2` を例にとると、Nginx に関連する主要なファイルとディレクトリには通常、次のものが含まれます。
@@ -138,6 +138,7 @@ nb proxy nginx reload
- `uploads`: `alias` を通じてアップロード ディレクトリを公開します
- `dist`: `alias` を通じてフロントエンド ビルド製品ディレクトリを公開します。
- `well-known`: OAuth / OpenID 関連の検出パスを処理します。
- `files`: `/files/` 配下のファイルアクセスリクエストをバックエンドアプリケーションへ転送します
- `api`: `/api/` リクエストをバックエンド アプリケーションに転送します
- `ws`: WebSocket リクエストをバックエンド アプリケーションに転送します。
- `spa`: `/` および `/v/` のフロントエンド エントリと `try_files` フォールバックを提供します
@@ -180,6 +181,11 @@ server {
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /files/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /api/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
@@ -229,7 +235,15 @@ nb proxy nginx generate --env test2 --host c.local.nocobase.com
2. 生成された結果に基づいて、ルーティング構造と実際のパスを確認します。
3. 次に、ドメイン名、実行モード、マウント パスに従って手動で調整します。
通常、この方法では、構成を最初から手書きするよりも、WebSocket、静的リソース、アップロード ディレクトリ、または SPA フォールバック ページに関連する詳細を見逃す可能性が低くなります。
通常、この方法では、構成を最初から手書きするよりも、`/files/`WebSocket、静的リソース、アップロードディレクトリ、SPA フォールバックページに関連する詳細を見逃しにくくなります。
:::warning 注意
`/files/` は NocoBase の認証を通す必要があるアプリケーションルートです。静的ディレクトリとして処理したり、SPA フォールバックへ流したりしないでください。NocoBase バックエンドへ転送し、`location /` などのフロントエンドフォールバックルールより前に配置します。
`APP_PUBLIC_PATH=/nocobase/` を設定している場合は、`/nocobase/files/` も転送してください。既存のファイル URL との互換性のため、ルートの `/files/` ルールも残します。
:::
## HTTPS の処理方法
+5
View File
@@ -59,6 +59,11 @@
"label": "Campo de Anexo",
"link": "/file-manager/field-attachment"
},
{
"type": "custom-link",
"label": "URL estável",
"link": "/file-manager/stable-url"
},
{
"type": "custom-link",
"label": "Pré-visualização de arquivos",
+57
View File
@@ -0,0 +1,57 @@
---
pkg: '@nocobase/plugin-file-manager'
title: "URL estável (URL de proxy)"
description: "Explica o formato, as permissões, os redirecionamentos e o comportamento das URLs estáveis de arquivos no NocoBase."
keywords: "URL estável,URL de proxy,URL permanente,acesso a arquivos,pré-visualização do Office,NocoBase"
---
# URL estável
Arquivos gerenciados por um mecanismo de armazenamento são acessados por uma **URL estável**. O NocoBase verifica o registro e as permissões e depois redireciona para a URL real gerada pelo armazenamento.
## Formato
```text
/files/<app>/<dataSource>/<collection>/<id><extname>
```
Com `APP_PUBLIC_PATH=/nocobase`, o caminho começa com `/nocobase/files/`. O ID e a extensão não podem ser alterados após a criação, mantendo a URL estável enquanto o registro existir.
| Uso | URL | Comportamento |
|---|---|---|
| Abrir | `/files/.../42.pdf` | Verifica a permissão e redireciona para o arquivo |
| Pré-visualizar | `/files/.../42.png?preview=1` | Redireciona para a miniatura ou pré-visualização |
| Baixar | `/files/.../42.pdf?download=1` | Redireciona com semântica de download |
| Office | `/files/.../42.xlsx?temporaryAccessToken=...` | Acesso temporário para o Office Online Viewer |
## Comportamento no NocoBase
- Campos de anexo, tabelas de arquivos e a [HTTP API](./http-api.md) retornam URLs estáveis em `url` e `preview`
- O Markdown salva a URL estável e pode usar S3, OSS, COS ou S3 Pro privados
- O campo URL de anexo preserva URLs externas inseridas manualmente e usa a URL estável para uploads gerenciados
- As pré-visualizações comuns usam a sessão e as permissões atuais do NocoBase
- Formulários públicos concedem acesso limitado apenas aos arquivos enviados na sessão atual do formulário
## Pré-visualização do Office
O Microsoft Office Online Viewer não pode usar o cookie do usuário. Ao abrir a pré-visualização, o NocoBase verifica a permissão e emite uma URL temporária vinculada ao arquivo. Ela dura 10 minutos por padrão e pode ser configurada entre 5 e 10 minutos com `TEMPORARY_FILE_ACCESS_EXPIRES_IN`.
Não salve essa URL em campos, Markdown ou dados de negócio e não a use como link de compartilhamento.
## Cuidados
- Estável não significa público; o destinatário ainda precisa de permissão
- Excluir ou mover o registro para outro contexto invalida a URL antiga
- A resposta é um redirecionamento `302`, que o cliente deve seguir
- Não persista `302 Location` nem `temporaryAccessToken`
- O proxy reverso deve encaminhar ao NocoBase a rota `/files/` sob `APP_PUBLIC_PATH`. Em implantações em subcaminhos, mantenha também a rota compatível `/files/` na raiz. As configurações geradas pela CLI do NocoBase incluem ambas as regras automaticamente
- Em implantações nas quais as páginas acessam a API entre origens (`API_BASE_URL` apontando para outra origem), adicione a origem da página a `CORS_ORIGIN_WHITELIST`. Caso contrário, o cookie de login nunca será armazenado e as URLs estáveis retornarão `403` por falta de credenciais. Consulte [Variáveis de ambiente](../get-started/installation/env.md#api_base_url)
- Use um `hostname` diferente para cada serviço NocoBase independente, em vez de diferenciá-los apenas pela porta. Os cookies do navegador não são isolados por porta; consulte [Implantação em produção](../get-started/deployment/production.md)
- Os subaplicativos da mesma implantação do NocoBase são diferenciados pelo nome do aplicativo e não precisam de hostnames separados. No entanto, um serviço independente em outra porta ainda precisa ser isolado por hostname se contiver um aplicativo principal ou subaplicativo com o mesmo nome
## Links relacionados
- [HTTP API](./http-api.md) — Enviar e consultar arquivos
- [Pré-visualização de arquivos](./file-preview/index.md) — Formatos compatíveis
- [Pré-visualização do Office](./file-preview/ms-office.md) — Configurar o Office Viewer
- [Mecanismos de armazenamento](./storage/index.md) — Configurar o armazenamento
@@ -2,12 +2,34 @@
Ao implantar o NocoBase em um ambiente de produção, a instalação de dependências pode ser um pouco trabalhosa devido às diferenças nos métodos de construção entre os diversos sistemas e ambientes. Para ter uma experiência funcional completa, recomendamos a implantação com **Docker**. Se o seu ambiente não puder usar o Docker, você também pode implantar usando o **create-nocobase-app**.
:::warning
:::warning Atenção
Não é recomendado implantar diretamente do código-fonte em um ambiente de produção. O código-fonte possui muitas dependências, é grande em tamanho e uma compilação completa exige bastante CPU e memória. Se você realmente precisar implantar a partir do código-fonte, sugerimos que primeiro construa uma imagem Docker personalizada e só então faça a implantação.
:::
:::warning Atenção
Ao implantar vários serviços NocoBase independentes, use um `hostname` diferente para cada serviço, como subdomínios distintos. Não diferencie os serviços apenas pela porta, como `https://example.com:13000` e `https://example.com:14000`.
O NocoBase usa cookies para manter o estado de login e as [permissões de acesso a arquivos](../../file-manager/stable-url.md). Os navegadores não isolam cookies por porta, portanto serviços em portas diferentes sob o mesmo `hostname` podem compartilhar cookies com o mesmo nome. Isso pode sobrescrever o estado de login ou causar falhas de autorização na pré-visualização e no download de arquivos.
Os subaplicativos na mesma implantação do NocoBase não estão sujeitos a essa restrição. Os cookies de login são diferenciados pelo nome do aplicativo, portanto o aplicativo principal e subaplicativos com nomes diferentes podem compartilhar o mesmo `hostname`.
No entanto, serviços independentes ainda precisam ser isolados. Se outro serviço NocoBase for executado em outra porta sob o mesmo `hostname` e contiver um aplicativo principal ou subaplicativo com o mesmo nome, os cookies ainda poderão entrar em conflito.
Use endereços como `app1.example.com` e `app2.example.com` e encaminhe-os para serviços NocoBase diferentes por meio do Nginx ou Caddy.
:::
## Frontend separado / Acesso a API entre origens
Prefira manter as páginas e a API na mesma origem: use um proxy reverso no mesmo domínio para encaminhar `${APP_PUBLIC_PATH}api/` e `${APP_PUBLIC_PATH}files/` para o serviço NocoBase e deixe `API_BASE_URL` vazio.
Se as páginas precisarem acessar a API entre origens (`API_BASE_URL` apontando para outra origem), adicione a origem da página a `CORS_ORIGIN_WHITELIST`. Caso contrário, o navegador ignorará `Set-Cookie` nas respostas da API, o cookie de login não será armazenado e a visualização e o download por URLs estáveis de arquivo falharão na autorização.
Observe também que os cookies são armazenados por `hostname`: quando as páginas e a API usam domínios totalmente diferentes, as requisições para `/files/` a partir do domínio da página não enviarão o cookie de login armazenado no domínio da API. Implantações assim devem ser alteradas para um proxy reverso de mesma origem. Consulte [Variáveis de ambiente](../installation/env.md#api_base_url).
## Processo de Implantação
Para a implantação em ambiente de produção, você pode consultar os passos de instalação e atualização já existentes.
@@ -39,4 +61,4 @@ Em um ambiente de produção, é recomendado gerenciar os recursos estáticos co
Dependendo do método de instalação, você pode usar os seguintes comandos para gerenciar o processo do NocoBase:
- [docker compose](./common-commands/docker-compose.md)
- [pm2](./common-commands/pm2.md)
- [pm2](./common-commands/pm2.md)
@@ -94,6 +94,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` permite que o contêiner do Caddy acesse o serviço `app` pela rede do Compose
- `./storage` precisa ser montado em `app` e `caddy` para compartilhar a configuração do proxy, os arquivos estáticos e os uploads
- O contêiner `caddy` deve esperar até que `nocobase.caddy` seja gerado e então criar um link para `/etc/caddy/Caddyfile` com `ln -sf`
- A configuração gerada encaminha ao NocoBase tanto a rota `/files/` sob `APP_PUBLIC_PATH` quanto a rota `/files/` na raiz, permitindo pré-visualizações e downloads autenticados
- Exponha ao host apenas a porta do contêiner Caddy. Para testes, você pode começar com `13000:80`; em produção, normalmente exponha diretamente as portas `80` e `443` do host, enquanto o serviço `app` não precisa expor sua porta para o host
## Se você usar Caddy local no host
@@ -169,6 +170,8 @@ sudo systemctl reload caddy
Se o Caddy do host não usar `/etc/caddy/Caddyfile`, substitua o caminho do link pelo seu próprio caminho de configuração. Normalmente é mais seguro manter `nocobase.caddy` como o arquivo principal de entrada em vez de copiar o conteúdo manualmente.
Se você mantiver o Caddy por conta própria em vez de usar a configuração gerada, certifique-se de que `/files/*` e a rota correspondente sob `APP_PUBLIC_PATH` sejam encaminhadas ao NocoBase antes das regras de fallback da SPA. Consulte [Proxy reverso Caddy](../../nocobase-cli/production/reverse-proxy/caddy.md) para ver um exemplo completo.
## Links relacionados
- [Instalação com Docker (Nginx embutido)](./docker.mdx) — Comece pela implantação de contêiner único
@@ -95,6 +95,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` permite que o contêiner do Nginx acesse o serviço `app` pela rede do Compose
- `./storage` precisa ser montado em `app` e `nginx` para compartilhar a configuração do proxy, os arquivos estáticos e os uploads
- O contêiner `nginx` deve esperar até que `nocobase.conf` seja gerado e então criar um link para `/etc/nginx/conf.d/default.conf` com `ln -sf`
- A configuração gerada encaminha ao NocoBase tanto a rota `/files/` sob `APP_PUBLIC_PATH` quanto a rota `/files/` na raiz, permitindo pré-visualizações e downloads autenticados
- Se você usar um contêiner externo do Nginx, deixe o contêiner `nginx` cuidar do mapeamento da porta do host. Para testes, você pode começar com `13000:80`; em produção, normalmente exponha diretamente as portas `80` e `443` do host, enquanto o serviço `app` não precisa expor sua porta para o host
## Se você usar Nginx local no host
@@ -170,6 +171,8 @@ sudo systemctl reload nginx
Se o Nginx do host não usar o diretório `conf.d`, substitua o caminho do link pelo seu próprio caminho de configuração. Normalmente é mais seguro manter `nocobase.conf` como um arquivo incluído a partir do contexto `http {}` em vez de copiar o conteúdo manualmente.
Se você mantiver o Nginx por conta própria em vez de usar a configuração gerada, certifique-se de que `/files/` e a rota correspondente sob `APP_PUBLIC_PATH` sejam encaminhadas ao NocoBase antes das regras de fallback da SPA. Consulte [Proxy reverso Nginx](../../nocobase-cli/production/reverse-proxy/nginx.md) para ver um exemplo completo.
## Links relacionados
- [Instalação com Docker (Nginx embutido)](./docker.mdx) — Comece pela implantação de contêiner único
@@ -627,7 +627,7 @@ Se você usa a imagem com Nginx embutido, normalmente é melhor não expor `1300
A configuração abaixo faz proxy das requisições do domínio para `http://127.0.0.1:13000/`:
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # Substitua your_domain.com pelo seu domínio
@@ -658,6 +658,8 @@ server {
Se você também quiser habilitar HTTPS, configure `443` e o certificado no Nginx do host. O contêiner do NocoBase não precisa lidar com certificados separadamente.
O bloco `location /` desta configuração na raiz também encaminha `/api/`, `/ws` e `/files/`. Se você separar os recursos estáticos das rotas da aplicação, garanta que `/files/` continue sendo encaminhado ao NocoBase e não seja tratado como um diretório estático.
### Implantação em subcaminho
Se você quiser implantar a aplicação em um subcaminho, por exemplo `https://your_domain.com/nocobase/`, configure primeiro a variável de ambiente `APP_PUBLIC_PATH`:
@@ -674,7 +676,7 @@ Mantenha o `/` no início e no fim do caminho. Depois da configuração, a URL d
Em seguida, configure o Nginx do host com o mesmo proxy de subcaminho:
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # Substitua your_domain.com pelo seu domínio
@@ -700,10 +702,32 @@ server {
send_timeout 600;
proxy_buffering off;
}
# Mantenha a compatibilidade com URLs de acesso a arquivos na raiz.
location ^~ /files/ {
proxy_pass http://127.0.0.1:13000;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $upstream_x_forwarded_proto;
proxy_set_header Host $final_host;
proxy_set_header Referer $http_referer;
proxy_set_header User-Agent $http_user_agent;
add_header Cache-Control "no-cache, no-store" always;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
}
}
```
O ponto principal é que `APP_PUBLIC_PATH` e o caminho em `proxy_pass` precisam permanecer iguais. Se `/nocobase/` faltar em um dos lados, os arquivos estáticos e o roteamento geralmente não funcionarão corretamente.
Observe estes pontos:
- `APP_PUBLIC_PATH` e o caminho em `proxy_pass` precisam permanecer iguais. Se `/nocobase/` faltar em um dos lados, os arquivos estáticos e o roteamento geralmente não funcionarão corretamente
- `/nocobase/files/` é encaminhado por `location /nocobase/`; a rota compatível `/files/` na raiz precisa ser encaminhada separadamente ao NocoBase
### Outras opções
@@ -86,6 +86,39 @@ API_BASE_PATH=/api/
### API_BASE_URL
URL base que o frontend usa para acessar a API do NocoBase. Fica vazia por padrão, o que significa usar `${APP_PUBLIC_PATH}api/` na mesma origem.
```bash
API_BASE_URL=
```
Configure-a com o endereço completo da API apenas quando as páginas e o serviço de API estiverem em origens diferentes (protocolo, domínio ou porta diferentes):
```bash
API_BASE_URL=https://api.example.com/api/
```
:::warning{title="Implantações entre origens"}
O NocoBase usa cookies para manter o estado de login e autorizar o acesso a [URLs estáveis de arquivo](../../file-manager/stable-url.md). Quando `API_BASE_URL` aponta para uma origem diferente da das páginas:
- A origem da página deve ser adicionada a [`CORS_ORIGIN_WHITELIST`](#cors_origin_whitelist). Caso contrário, o navegador ignorará `Set-Cookie` nas respostas da API, o cookie de login não será armazenado e recursos que dependem de cookie, como visualização e download de arquivos, falharão com `403`.
- Os cookies são armazenados por `hostname`. Se as páginas e a API usarem domínios totalmente diferentes, requisições para URLs estáveis em `/files/` a partir do domínio da página não enviarão o cookie de login armazenado no domínio da API, então o acesso ao arquivo continuará falhando.
Prefira servir as páginas e a API na mesma origem por meio de um proxy reverso e deixar `API_BASE_URL` vazio.
:::
### CORS_ORIGIN_WHITELIST
Lista de origens autorizadas a acessar a API entre origens com credenciais (cookies). Separe várias origens com vírgulas. Vazia por padrão.
```bash
CORS_ORIGIN_WHITELIST=https://www.example.com,https://admin.example.com
```
- Quando não configurada, apenas requisições da mesma origem são tratadas como confiáveis; requisições entre origens ainda podem chamar a API anonimamente, mas o navegador não pode ler nem gravar cookies para elas.
- Quando configurada, as origens na lista recebem `Access-Control-Allow-Origin` refletindo exatamente a origem e `Access-Control-Allow-Credentials: true`, permitindo que o navegador envie e armazene cookies de login em requisições entre origens.
- A API de login valida `Origin` e `Referer` da requisição; requisições de login entre origens vindas de fora da lista são rejeitadas com `403`.
### CLUSTER_MODE
> `v1.6.0+`
@@ -69,6 +69,16 @@ Se acontecer de você ficar preso aqui "Por que você precisa de `nb app autosta
- Se você for se conectar ao proxy reverso, `appPort` foi salvo no env
- Se você está pronto para abri-lo oficialmente para o mundo exterior, você já planejou o nome de domínio, a porta de entrada e a solução HTTPS.
:::warning Atenção
Use um `hostname` diferente, como um subdomínio separado, para cada serviço NocoBase independente. Não diferencie os serviços apenas pela porta. Os cookies do navegador não são isolados por porta, portanto serviços sob o mesmo `hostname` podem sobrescrever o estado de login e afetar a autorização das [URLs estáveis](../../file-manager/stable-url.md).
Os subaplicativos na mesma implantação do NocoBase são diferenciados pelo nome do aplicativo e não precisam de hostnames separados. No entanto, se outro serviço NocoBase independente for executado em outra porta sob o mesmo `hostname` e contiver um aplicativo principal ou subaplicativo com o mesmo nome, os cookies ainda poderão entrar em conflito.
Por exemplo, use `app1.example.com` e `app2.example.com` em vez de `example.com:13000` e `example.com:14000`.
:::
Se você não concluiu a instalação da CLI ou a inicialização do ambiente, volte para [Instalação usando CLI (recomendado)](../installation/cli.md).
Se o comando solicitar que env está faltando `appPort`, primeiro execute [`nb env update`](../../api/cli/env/update.md) para preenchê-lo.
@@ -124,7 +124,7 @@ Se quiser compensar a configuração no nível do site do Caddy, como cabeçalho
Se o seu aplicativo não estiver hospedado na CLI ou se você desejar explicitamente manter a configuração completa do Caddy, também poderá escrevê-lo manualmente.
Entretanto, para NocoBase, a entrada do ambiente de produção geralmente não é apenas um simples `reverse_proxy`. Além de encaminhar solicitações de API para o aplicativo de back-end, uma configuração Caddy completa e funcional geralmente também precisa lidar com o diretório de upload, recursos estáticos de front-end, roteamento `.well-known`, WebSocket e página de fallback de SPA.
Entretanto, para o NocoBase, a entrada do ambiente de produção geralmente não é apenas um simples `reverse_proxy`. Além de encaminhar solicitações de API para o aplicativo de back-end, uma configuração Caddy completa também precisa tratar o diretório de upload, recursos estáticos de front-end, a rota de acesso a arquivos `/files/`, o roteamento `.well-known`, WebSocket e as páginas de fallback da SPA.
Tomando `test2` como exemplo, os principais diretórios relacionados ao Caddy geralmente incluem:
@@ -139,6 +139,7 @@ Em outras palavras, a configuração manuscrita geralmente precisa cobrir pelo m
- `dist`: Exponha o diretório do produto de compilação front-end
- `oauth well-known`: Lidar com caminhos de descoberta OAuth
- `openid well-known`: Lidar com caminhos de descoberta OpenID
- `files`: encaminhar solicitações de acesso a arquivos sob `/files/` para o aplicativo de back-end
- `api`: encaminha a solicitação `/api/` para o aplicativo back-end
- `ws`: encaminha solicitações WebSocket para o aplicativo backend
- `spa v2`: Fornece entrada de front-end e página de retorno para `/v/`
@@ -187,6 +188,10 @@ c.local.nocobase.com {
reverse_proxy host.docker.internal:56575
}
handle /files/* {
reverse_proxy host.docker.internal:56575
}
handle /api/* {
reverse_proxy host.docker.internal:56575
}
@@ -249,7 +254,15 @@ Uma abordagem mais prudente é geralmente:
2. Confirme a estrutura de roteamento e o caminho real com base nos resultados gerados.
3. Em seguida, faça ajustes manuais de acordo com seu nome de domínio, modo de execução e caminho de montagem.
Geralmente, é menos provável que perca detalhes relacionados a WebSockets, recursos estáticos, diretórios de upload, rotas `.well-known` ou páginas substitutas de SPA do que escrever uma configuração à mão do zero.
Geralmente, é menos provável que você deixe de tratar detalhes relacionados a `/files/`, WebSockets, recursos estáticos, diretórios de upload, rotas `.well-known` ou páginas de fallback da SPA do que ao escrever uma configuração do zero.
:::warning Atenção
`/files/` é uma rota da aplicação que precisa passar pela autorização do NocoBase. Não a trate como um diretório estático nem permita que ela caia no fallback da SPA. Encaminhe-a para o back-end do NocoBase e coloque a regra antes de `handle_path /*` e das demais regras de fallback do front-end.
Se `APP_PUBLIC_PATH=/nocobase/` estiver configurado, encaminhe também `/nocobase/files/*`. Mantenha a regra `/files/*` na raiz para compatibilidade com URLs de arquivos existentes.
:::
## Verifique e recarregue a configuração
@@ -9,7 +9,7 @@ keywords: "NocoBase,nb proxy nginx,nb proxy caddy, proxy reverso, Nginx, Caddy,
Este artigo se aplica apenas a aplicativos instalados usando `nb init`.
No NocoBase, o proxy reverso do ambiente de produção faz mais do que simplesmente encaminhar solicitações para o processo de aplicação. Freqüentemente, os detalhes de WebSockets, subcaminhos, recursos estáticos de front-end, diretórios de upload e páginas substitutas de SPA também são tratados ao mesmo tempo.
No NocoBase, o proxy reverso do ambiente de produção faz mais do que encaminhar solicitações para o processo da aplicação. Ele também precisa tratar WebSockets, subcaminhos, recursos estáticos de front-end, diretórios de upload, a rota de acesso a arquivos `/files/` e as páginas de fallback da SPA.
A função de `nb proxy` é coletar esses detalhes facilmente perdidos em um conjunto estável de entradas de comando.
@@ -122,7 +122,7 @@ Se você deseja adicionar configuração Nginx em nível de site, como limitaç
Se o seu aplicativo não estiver hospedado na CLI ou se você desejar explicitamente manter a configuração completa do Nginx, também poderá escrevê-lo manualmente.
No entanto, para NocoBase, o proxy reverso de produção geralmente é mais do que um simples `proxy_pass`. Além de encaminhar solicitações de API para o aplicativo de back-end, uma configuração completa e utilizável geralmente precisa lidar com o diretório de upload, recursos estáticos de front-end, WebSocket, rota `.well-known` e página de fallback do SPA.
No entanto, para o NocoBase, o proxy reverso de produção geralmente é mais do que um simples `proxy_pass`. Além de encaminhar solicitações de API para o aplicativo de back-end, uma configuração completa também precisa tratar o diretório de upload, recursos estáticos de front-end, a rota de acesso a arquivos `/files/`, WebSocket, a rota `.well-known` e as páginas de fallback da SPA.
Tomando `test2` como exemplo, os principais arquivos e diretórios relacionados ao Nginx geralmente incluem:
@@ -138,6 +138,7 @@ Em outras palavras, a configuração manuscrita geralmente precisa cobrir pelo m
- `uploads`: exponha o diretório de upload por meio de `alias`
- `dist`: exponha o diretório do produto de compilação front-end por meio de `alias`
- `well-known`: Lidar com caminhos de descoberta relacionados a OAuth/OpenID
- `files`: encaminhar solicitações de acesso a arquivos sob `/files/` para o aplicativo de back-end
- `api`: encaminha a solicitação `/api/` para o aplicativo back-end
- `ws`: encaminha solicitações WebSocket para o aplicativo backend
- `spa`: fornece entrada de front-end e substituto `try_files` para `/` e `/v/`
@@ -180,6 +181,11 @@ server {
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /files/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /api/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
@@ -229,7 +235,15 @@ Uma abordagem mais prudente é geralmente:
2. Confirme a estrutura de roteamento e o caminho real com base nos resultados gerados.
3. Em seguida, faça ajustes manuais de acordo com seu nome de domínio, modo de execução e caminho de montagem.
Geralmente, é menos provável que perca detalhes relacionados a WebSockets, recursos estáticos, diretórios de upload ou páginas substitutas de SPA do que escrever uma configuração à mão do zero.
Geralmente, é menos provável que você deixe de tratar detalhes relacionados a `/files/`, WebSockets, recursos estáticos, diretórios de upload ou páginas de fallback da SPA do que ao escrever uma configuração do zero.
:::warning Atenção
`/files/` é uma rota da aplicação que precisa passar pela autorização do NocoBase. Não a trate como um diretório estático nem permita que ela caia no fallback da SPA. Encaminhe-a para o back-end do NocoBase e coloque a regra antes de `location /` e das demais regras de fallback do front-end.
Se `APP_PUBLIC_PATH=/nocobase/` estiver configurado, encaminhe também `/nocobase/files/`. Mantenha a regra `/files/` na raiz para compatibilidade com URLs de arquivos existentes.
:::
## Como lidar com HTTPS
+5
View File
@@ -59,6 +59,11 @@
"label": "Поле вложения",
"link": "/file-manager/field-attachment"
},
{
"type": "custom-link",
"label": "Стабильный URL",
"link": "/file-manager/stable-url"
},
{
"type": "custom-link",
"label": "Предпросмотр файлов",
+57
View File
@@ -0,0 +1,57 @@
---
pkg: '@nocobase/plugin-file-manager'
title: "Стабильный URL (прокси-URL)"
description: "Описание формата, прав доступа, перенаправлений и поведения стабильных URL файлов в NocoBase."
keywords: "стабильный URL,прокси-URL,постоянный URL,доступ к файлам,предпросмотр Office,NocoBase"
---
# Стабильный URL
Файлы, управляемые хранилищем NocoBase, доступны через **стабильный URL**. NocoBase проверяет запись файла и права доступа, а затем перенаправляет запрос на фактический URL, созданный хранилищем.
## Формат
```text
/files/<app>/<dataSource>/<collection>/<id><extname>
```
При `APP_PUBLIC_PATH=/nocobase` путь начинается с `/nocobase/files/`. ID и расширение нельзя изменить после создания, поэтому URL остаётся стабильным, пока существует запись.
| Назначение | URL | Поведение |
|---|---|---|
| Открытие | `/files/.../42.pdf` | Проверяет права и перенаправляет к файлу |
| Предпросмотр | `/files/.../42.png?preview=1` | Перенаправляет к миниатюре или версии для просмотра |
| Скачивание | `/files/.../42.pdf?download=1` | Перенаправляет с режимом скачивания |
| Office | `/files/.../42.xlsx?temporaryAccessToken=...` | Временный доступ для Office Online Viewer |
## Поведение в NocoBase
- Поля вложений, таблицы файлов и [HTTP API](./http-api.md) возвращают стабильные значения `url` и `preview`
- Markdown сохраняет стабильный URL и поддерживает закрытые S3, OSS, COS и S3 Pro
- Поле URL вложения сохраняет введённые вручную внешние URL, а для управляемых файлов использует стабильный URL
- Обычный предпросмотр использует текущую сессию и права NocoBase
- Публичная форма даёт ограниченный доступ только к файлам, загруженным в текущей сессии формы
## Предпросмотр Office
Microsoft Office Online Viewer не может использовать cookie пользователя NocoBase. При открытии NocoBase сначала проверяет право просмотра, а затем выдаёт временный URL, привязанный к файлу. По умолчанию он действует 10 минут; параметр `TEMPORARY_FILE_ACCESS_EXPIRES_IN` допускает значение от 5 до 10 минут.
Не сохраняйте временный URL в полях, Markdown или бизнес-данных и не используйте его как ссылку общего доступа.
## Важные замечания
- Стабильный не означает публичный; получателю всё равно нужны права
- Удаление или перенос записи делает старый URL недействительным
- Ответ представляет собой перенаправление `302`, которому должен следовать клиент
- Не сохраняйте `302 Location` и `temporaryAccessToken`
- Обратный прокси должен передавать маршрут `/files/` в пределах `APP_PUBLIC_PATH` в NocoBase. При развёртывании в подпути также сохраните совместимый корневой маршрут `/files/`. Конфигурации, созданные NocoBase CLI, автоматически включают оба правила
- В развёртываниях, где страницы обращаются к API между разными origin (`API_BASE_URL` указывает на другой origin), origin страницы нужно добавить в `CORS_ORIGIN_WHITELIST`. Иначе cookie входа не будет сохранена, а stable URL вернёт `403` из-за отсутствия учётных данных. См. [Переменные окружения](../get-started/installation/env.md#api_base_url)
- Используйте отдельный `hostname` для каждого независимого сервиса NocoBase, а не различайте сервисы только по порту. Cookies браузера не изолируются по портам; см. [Развёртывание в рабочей среде](../get-started/deployment/production.md)
- Подприложения в одном развёртывании NocoBase различаются по имени приложения и не требуют отдельных hostnames. Однако независимый сервис на другом порту всё равно должен быть изолирован по hostname, если он содержит основное или дочернее приложение с тем же именем
## Связанные ссылки
- [HTTP API](./http-api.md) — Загрузка и получение файлов
- [Предпросмотр файлов](./file-preview/index.md) — Поддерживаемые форматы
- [Предпросмотр Office](./file-preview/ms-office.md) — Настройка Office Viewer
- [Хранилища](./storage/index.md) — Настройка файлового хранилища
@@ -2,12 +2,34 @@
При развёртывании NocoBase в производственной среде установка зависимостей может быть затруднительной из-за различий в методах сборки для разных систем и окружений. Для полноценной функциональности мы рекомендуем разворачивать с **Docker**. Если ваша среда не может использовать Docker, вы также можете развернуть с помощью **create-nocobase-app**.
:::warning
:::warning Внимание
Развёртывать напрямую из исходного кода в производственной среде не рекомендуется. Исходный код имеет множество зависимостей, большой объем и при полной компиляции требуются значительные ресурсы CPU и памяти. Если вам необходимо разворачивать из исходников, рекомендуется сначала собрать собственный Docker-образ, а затем выполнить развёртывание.
:::
:::warning Внимание
Если вы развёртываете несколько независимых сервисов NocoBase, используйте отдельный `hostname` для каждого сервиса, например разные поддомены. Не различайте сервисы только по порту, как в `https://example.com:13000` и `https://example.com:14000`.
NocoBase использует cookies для сохранения состояния входа и [прав доступа к файлам](../../file-manager/stable-url.md). Браузеры не изолируют cookies по портам, поэтому сервисы на разных портах под одним `hostname` могут использовать одноимённые cookies. Это может привести к перезаписи состояния входа или ошибкам авторизации при предварительном просмотре и скачивании файлов.
Подприложения в одном развёртывании NocoBase не подпадают под это ограничение. Cookies входа различаются по имени приложения, поэтому основное приложение и подприложения с разными именами могут использовать один `hostname`.
Однако независимые сервисы по-прежнему необходимо изолировать. Если другой сервис NocoBase работает на другом порту под тем же `hostname` и содержит основное или дочернее приложение с тем же именем, cookies всё равно могут конфликтовать.
Используйте адреса наподобие `app1.example.com` и `app2.example.com`, а затем направляйте их к разным сервисам NocoBase через Nginx или Caddy.
:::
## Разделённый фронтенд / Межсайтовый доступ к API
Рекомендуется держать страницы и API на одном origin: используйте обратный прокси под одним доменом, чтобы направлять `${APP_PUBLIC_PATH}api/` и `${APP_PUBLIC_PATH}files/` в сервис NocoBase, а `API_BASE_URL` оставьте пустым.
Если страницы должны обращаться к API с другого origin (`API_BASE_URL` указывает на другой origin), добавьте origin страницы в `CORS_ORIGIN_WHITELIST`. Иначе браузер проигнорирует `Set-Cookie` в ответах API, cookie входа не будет сохранена, а предпросмотр и скачивание через stable file URL завершатся ошибкой авторизации.
Также учитывайте, что cookies хранятся по `hostname`: если страницы и API используют полностью разные домены, запросы к `/files/` с домена страницы не будут отправлять cookie входа, сохранённую для домена API. Для таких развёртываний следует перейти на same-origin reverse proxy. См. [Переменные окружения](../installation/env.md#api_base_url).
## Процесс развёртывания
Для развёртывания в производственной среде вы можете обратиться к существующим шагам установки и обновления.
@@ -94,6 +94,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` позволяет контейнеру Caddy обращаться к сервису `app` через сеть Compose
- `./storage` нужно смонтировать и в `app`, и в `caddy`, чтобы они могли совместно использовать конфигурацию прокси, статические ресурсы и загруженные файлы
- Контейнер `caddy` должен дождаться создания `nocobase.caddy`, а затем с помощью `ln -sf` связать его с `/etc/caddy/Caddyfile`
- Созданная конфигурация передаёт в NocoBase как маршрут `/files/` в пределах `APP_PUBLIC_PATH`, так и корневой маршрут `/files/`, обеспечивая авторизованный предпросмотр и скачивание файлов
- На хост нужно публиковать только порт контейнера Caddy. Для тестирования можно начать с `13000:80`; в production обычно напрямую публикуют порты хоста `80` и `443`, а сервису `app` не нужно публиковать порт на хост
## Если используется локальный Caddy на хосте
@@ -169,6 +170,8 @@ sudo systemctl reload caddy
Если ваш локальный Caddy не использует `/etc/caddy/Caddyfile`, замените путь ссылки на свой путь конфигурации. Обычно безопаснее оставлять `nocobase.caddy` как основной входной файл, а не копировать его содержимое вручную.
Если вы управляете Caddy самостоятельно и не используете созданную конфигурацию, убедитесь, что `/files/*` и соответствующий маршрут в пределах `APP_PUBLIC_PATH` передаются в NocoBase до правил резервной страницы SPA. Полный пример см. в разделе [Обратный прокси Caddy](../../nocobase-cli/production/reverse-proxy/caddy.md).
## Связанные ссылки
- [Установка через Docker (встроенный Nginx)](./docker.mdx) — Начните с одноконтейнерного варианта
@@ -95,6 +95,7 @@ services:
- `NOCOBASE_PROXY_UPSTREAM_HOST=app` позволяет контейнеру Nginx обращаться к сервису `app` через сеть Compose
- `./storage` нужно смонтировать и в `app`, и в `nginx`, чтобы они могли совместно использовать конфигурацию прокси, статические ресурсы и загруженные файлы
- Контейнер `nginx` должен дождаться создания `nocobase.conf`, а затем с помощью `ln -sf` связать его с `/etc/nginx/conf.d/default.conf`
- Созданная конфигурация передаёт в NocoBase как маршрут `/files/` в пределах `APP_PUBLIC_PATH`, так и корневой маршрут `/files/`, обеспечивая авторизованный предпросмотр и скачивание файлов
- Если вы используете внешний контейнер Nginx, пусть контейнер `nginx` управляет пробросом порта хоста. Для тестирования можно начать с `13000:80`; в production обычно напрямую публикуют порты хоста `80` и `443`, а сервису `app` не нужно публиковать порт на хост
## Если используется локальный Nginx на хосте
@@ -170,6 +171,8 @@ sudo systemctl reload nginx
Если ваш локальный Nginx не использует каталог `conf.d`, замените путь ссылки на свой путь конфигурации. Обычно безопаснее оставлять `nocobase.conf` как файл, который подключается из контекста `http {}`, а не копировать его содержимое вручную.
Если вы управляете Nginx самостоятельно и не используете созданную конфигурацию, убедитесь, что `/files/` и соответствующий маршрут в пределах `APP_PUBLIC_PATH` передаются в NocoBase до правил резервной страницы SPA. Полный пример см. в разделе [Обратный прокси Nginx](../../nocobase-cli/production/reverse-proxy/nginx.md).
## Связанные ссылки
- [Установка через Docker (встроенный Nginx)](./docker.mdx) — Начните с одноконтейнерного варианта
@@ -627,7 +627,7 @@ app-postgres-app-1 | 🚀 NocoBase server running at: http://localhost:13000/
Следующая конфигурация проксирует запросы к домену на `http://127.0.0.1:13000/`:
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # Замените your_domain.com на ваш домен
@@ -658,6 +658,8 @@ server {
Если вы также хотите включить HTTPS, настройте `443` и сертификат в Nginx на хосте. Контейнеру NocoBase не нужно отдельно обрабатывать сертификаты.
Блок `location /` в этой конфигурации для корневого пути также проксирует `/api/`, `/ws` и `/files/`. Если вы разделяете статические ресурсы и маршруты приложения, убедитесь, что `/files/` по-прежнему передаётся в NocoBase и не обрабатывается как статический каталог.
### Развертывание в подпути
Если вы хотите развернуть приложение в подпути, например `https://your_domain.com/nocobase/`, сначала настройте переменную окружения `APP_PUBLIC_PATH`:
@@ -674,7 +676,7 @@ services:
Затем настройте Nginx на хосте с тем же подпутем:
```bash
```nginx
server {
listen 80;
server_name your_domain.com; # Замените your_domain.com на ваш домен
@@ -700,10 +702,32 @@ server {
send_timeout 600;
proxy_buffering off;
}
# Сохранить совместимость с URL доступа к файлам на корневом уровне.
location ^~ /files/ {
proxy_pass http://127.0.0.1:13000;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $upstream_x_forwarded_proto;
proxy_set_header Host $final_host;
proxy_set_header Referer $http_referer;
proxy_set_header User-Agent $http_user_agent;
add_header Cache-Control "no-cache, no-store" always;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
}
}
```
Главное — чтобы `APP_PUBLIC_PATH` и путь в `proxy_pass` совпадали. Если с одной из сторон отсутствует `/nocobase/`, статические ресурсы и маршрутизация обычно работают некорректно.
Обратите внимание на следующее:
- `APP_PUBLIC_PATH` и путь в `proxy_pass` должны совпадать. Если с одной из сторон отсутствует `/nocobase/`, статические ресурсы и маршрутизация обычно работают некорректно
- `/nocobase/files/` передаётся через `location /nocobase/`; совместимый корневой маршрут `/files/` необходимо отдельно передавать в NocoBase
### Другие варианты
@@ -86,6 +86,39 @@ API_BASE_PATH=/api/
### API_BASE_URL
Базовый URL, который фронтенд использует для доступа к API NocoBase. По умолчанию пустой, что означает использование same-origin `${APP_PUBLIC_PATH}api/`.
```bash
API_BASE_URL=
```
Указывайте полный адрес API только тогда, когда страницы и сервис API находятся на разных origin (отличается протокол, домен или порт):
```bash
API_BASE_URL=https://api.example.com/api/
```
:::warning{title="Кросс-origin развёртывания"}
NocoBase использует cookies для сохранения состояния входа и авторизации доступа к [stable file URL](../../file-manager/stable-url.md). Когда `API_BASE_URL` указывает на origin, отличный от origin страниц:
- Origin страницы должен быть добавлен в [`CORS_ORIGIN_WHITELIST`](#cors_origin_whitelist). Иначе браузер проигнорирует `Set-Cookie` в ответах API, cookie входа не будет сохранена, а функции, зависящие от cookies, например предпросмотр и скачивание файлов, будут завершаться `403`.
- Cookies хранятся по `hostname`. Если страницы и API используют полностью разные домены, запросы к stable URL в `/files/` с домена страницы не отправят cookie входа, сохранённую для домена API, поэтому доступ к файлу всё равно не сработает.
Поэтому рекомендуется отдавать страницы и API с одного origin через обратный прокси и оставлять `API_BASE_URL` пустым.
:::
### CORS_ORIGIN_WHITELIST
Белый список origin, которым разрешён кросс-origin доступ к API с учётными данными (cookies). Несколько origin указываются через запятую. По умолчанию пусто.
```bash
CORS_ORIGIN_WHITELIST=https://www.example.com,https://admin.example.com
```
- Если список не настроен, доверенными считаются только same-origin запросы; кросс-origin запросы всё ещё могут анонимно вызывать API, но браузеру не разрешается читать или записывать для них cookies.
- Если список настроен, origin из белого списка получают точный `Access-Control-Allow-Origin` и `Access-Control-Allow-Credentials: true`, что позволяет браузеру отправлять и сохранять cookies входа в кросс-origin запросах.
- API входа проверяет `Origin` / `Referer` запроса; кросс-origin запросы на вход с origin вне белого списка отклоняются с `403`.
### CLUSTER_MODE
> `v1.6.0+`
@@ -69,6 +69,16 @@ nb app autostart run
- Если вы собираетесь подключиться к обратному прокси, `appPort` сохранен в env.
- Если вы готовы официально открыть его внешнему миру, вы уже запланировали доменное имя, входной порт и решение HTTPS.
:::warning Внимание
Используйте отдельный `hostname`, например отдельный поддомен, для каждого независимого сервиса NocoBase. Не различайте сервисы только по порту. Cookies браузера не изолируются по портам, поэтому сервисы под одним `hostname` могут перезаписать состояние входа и повлиять на авторизацию [стабильных URL](../../file-manager/stable-url.md).
Подприложения в одном развёртывании NocoBase различаются по имени приложения и не требуют отдельных hostnames. Однако если другой независимый сервис NocoBase работает на другом порту под тем же `hostname` и содержит основное или дочернее приложение с тем же именем, cookies всё равно могут конфликтовать.
Например, используйте `app1.example.com` и `app2.example.com` вместо `example.com:13000` и `example.com:14000`.
:::
Если вы не завершили установку CLI или инициализацию среды, вернитесь к [Установка с помощью CLI (рекомендуется)](../installation/cli.md).
Если команда подскажет, что в env отсутствует `appPort`, сначала выполните [`nb env update`](../../api/cli/env/update.md), чтобы заполнить его.
@@ -124,7 +124,7 @@ nb proxy caddy reload
Если ваше приложение не размещено в CLI или вы явно хотите поддерживать полную конфигурацию Caddy самостоятельно, вы также можете написать ее вручную.
Однако для NocoBase запись производственной среды обычно представляет собой не просто `reverse_proxy`. Помимо пересылки запросов API серверному приложению, полная и работающая конфигурация Caddy обычно также должна обрабатывать каталог загрузки, статические ресурсы внешнего интерфейса, маршрутизацию `.well-known`, WebSocket и резервную страницу SPA.
Однако для NocoBase вход производственной среды обычно представляет собой не просто `reverse_proxy`. Помимо пересылки запросов API серверному приложению, полная конфигурация Caddy должна обрабатывать каталог загрузки, статические ресурсы интерфейса, маршрут доступа к файлам `/files/`, маршрутизацию `.well-known`, WebSocket и резервные страницы SPA.
Если взять в качестве примера `test2`, ключевые каталоги, связанные с Caddy, обычно включают в себя:
@@ -139,6 +139,7 @@ nb proxy caddy reload
- `dist`: открыть каталог продукта внешней сборки.
`oauth well-known`: обработка путей обнаружения OAuth.
- `openid well-known`: обработка путей обнаружения OpenID.
- `files`: передача запросов доступа к файлам в `/files/` серверному приложению
- `api`: переслать запрос `/api/` серверному приложению.
- `ws`: пересылать запросы WebSocket серверному приложению.
- `spa v2`: предоставляет интерфейсную страницу ввода и возврата для `/v/`.
@@ -187,6 +188,10 @@ c.local.nocobase.com {
reverse_proxy host.docker.internal:56575
}
handle /files/* {
reverse_proxy host.docker.internal:56575
}
handle /api/* {
reverse_proxy host.docker.internal:56575
}
@@ -249,7 +254,15 @@ NB_CLI_ROOT/test2/storage/uploads
2. Подтвердите структуру маршрутизации и фактический путь на основе сгенерированных результатов.
3. Затем вручную выполните настройки в соответствии с вашим доменным именем, режимом работы и путем монтирования.
Обычно при этом меньше шансов пропустить детали, связанные с WebSockets, статическими ресурсами, каталогами загрузки, маршрутами `.well-known` или резервными страницами SPA, чем при написании конфигурации вручную с нуля.
Обычно при этом меньше шансов пропустить детали, связанные с `/files/`, WebSockets, статическими ресурсами, каталогами загрузки, маршрутами `.well-known` или резервными страницами SPA, чем при написании конфигурации вручную с нуля.
:::warning Внимание
`/files/` — это маршрут приложения, который должен проходить авторизацию NocoBase. Не обрабатывайте его как статический каталог и не допускайте его попадания в резервную страницу SPA. Передавайте маршрут серверной части NocoBase и размещайте правило перед `handle_path /*` и другими правилами резервной обработки интерфейса.
Если настроен `APP_PUBLIC_PATH=/nocobase/`, также передавайте `/nocobase/files/*`. Сохраните корневое правило `/files/*` для совместимости с существующими URL файлов.
:::
## Проверьте и перезагрузите конфигурацию
@@ -9,7 +9,7 @@ keywords: "NocoBase, nb proxy nginx, nb proxy caddy, обратный прокс
Эта статья относится только к приложениям, установленным с помощью `nb init`.
В NocoBase обратный прокси-сервер производственной среды делает больше, чем просто перенаправляет запросы в процесс приложения. Часто одновременно обрабатываются сведения о WebSockets, подпутях, статических ресурсах внешнего интерфейса, каталогах загрузки и резервных страницах SPA.
В NocoBase обратный прокси производственной среды не только перенаправляет запросы в процесс приложения. Он также должен обрабатывать WebSockets, подпути, статические ресурсы интерфейса, каталоги загрузки, маршрут доступа к файлам `/files/` и резервные страницы SPA.
Функция `nb proxy` состоит в том, чтобы собрать эти легко упускаемые детали в стабильный набор командных записей.
@@ -122,7 +122,7 @@ nb proxy nginx reload
Если ваше приложение не размещено через CLI или вы явно хотите поддерживать полную конфигурацию Nginx самостоятельно, вы также можете написать ее вручную.
Однако для NocoBase рабочий обратный прокси-сервер обычно представляет собой нечто большее, чем простой `proxy_pass`. Помимо пересылки запросов API серверному приложению, полная и полезная конфигурация обычно требует обработки каталога загрузки, статических ресурсов внешнего интерфейса, WebSocket, маршрута `.well-known` и резервной страницы SPA.
Однако для NocoBase рабочий обратный прокси обычно представляет собой нечто большее, чем простой `proxy_pass`. Помимо пересылки запросов API серверному приложению, полная конфигурация должна обрабатывать каталог загрузки, статические ресурсы интерфейса, маршрут доступа к файлам `/files/`, WebSocket, маршрут `.well-known` и резервные страницы SPA.
Если взять в качестве примера `test2`, ключевые файлы и каталоги, связанные с Nginx, обычно включают:
@@ -138,6 +138,7 @@ nb proxy nginx reload
`uploads`: откройте каталог загрузки через `alias`.
`dist`: откройте каталог продукта внешней сборки через `alias`.
- `well-known`: обработка путей обнаружения, связанных с OAuth и OpenID.
- `files`: передача запросов доступа к файлам в `/files/` серверному приложению
- `api`: переслать запрос `/api/` серверному приложению.
- `ws`: пересылать запросы WebSocket серверному приложению.
`spa`: обеспечивает вход через интерфейс и резервный вариант `try_files` для `/` и `/v/`.
@@ -180,6 +181,11 @@ server {
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /files/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
}
location ^~ /api/ {
proxy_pass http://127.0.0.1:56575;
include NB_CLI_ROOT/.nocobase/proxy/nginx/snippets/proxy-location.conf;
@@ -229,7 +235,15 @@ nb proxy nginx generate --env test2 --host c.local.nocobase.com
2. Подтвердите структуру маршрутизации и фактический путь на основе сгенерированных результатов.
3. Затем вручную выполните настройки в соответствии с вашим доменным именем, режимом работы и путем монтирования.
Обычно при этом меньше вероятность пропустить детали, связанные с WebSockets, статическими ресурсами, каталогами загрузки или резервными страницами SPA, чем при написании конфигурации вручную с нуля.
Обычно при этом меньше вероятность пропустить детали, связанные с `/files/`, WebSockets, статическими ресурсами, каталогами загрузки или резервными страницами SPA, чем при написании конфигурации вручную с нуля.
:::warning Внимание
`/files/` — это маршрут приложения, который должен проходить авторизацию NocoBase. Не обрабатывайте его как статический каталог и не допускайте его попадания в резервную страницу SPA. Передавайте маршрут серверной части NocoBase и размещайте правило перед `location /` и другими правилами резервной обработки интерфейса.
Если настроен `APP_PUBLIC_PATH=/nocobase/`, также передавайте `/nocobase/files/`. Сохраните корневое правило `/files/` для совместимости с существующими URL файлов.
:::
## Как работать с HTTPS
+5
View File
@@ -59,6 +59,11 @@
"label": "Field Attachment",
"link": "/file-manager/field-attachment"
},
{
"type": "custom-link",
"label": "URL ổn định",
"link": "/file-manager/stable-url"
},
{
"type": "custom-link",
"label": "Xem trước file",

Some files were not shown because too many files have changed in this diff Show More