Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

在非根路径下部署

Deploying at Non-Root Paths

到目前为止,部署步骤都假设你的应用部署在域名的根路径(/)。然而,也可以将应用部署在非根路径,例如 /my-app

So far, the deployment steps have assumed that your application is deployed at the root path of your domain (/). However, it is also possible to deploy your application at a non-root path, such as /my-app.

如果你正在非根路径部署,你需要采取一些步骤来告诉应用的各个部分新的基础路径是什么。

If you are deploying at a non-root path, you’ll need to take a few steps to tell the various parts of the application what that new base path is.

更新路由器的 base

Update the Router base

<Router/> 组件有一个 base 属性,用于指定路由的基础路径。例如,如果你正在部署一个包含 //about/contact 三个页面的应用,并且你想将它们部署在 /my-app 下,使得三个路由变为 /my-app/my-app/about/my-app/contact,你需要将 base 属性设置为 /my-app

The <Router/> component has a base prop that specifies the base path for routing. For example, if you are deploying an application with three pages /, /about, and /contact, and you want them to be deployed at /my-app so that the three routes are /my-app, /my-app/about, and /my-app/contact, you would set the base prop to /my-app:

<Router base="/my-app">
    <Routes fallback=|| "Not found.">
        <Route path=path!("/") view=Home/>
        <Route path=path!("/about") view=About/>
        <Route path=path!("/contact") view=Contact/>
    </Routes>
</Router>

如果你正在使用反向代理,你的服务器可能会认为它正在提供 / 路径的服务,而实际上它是在提供 /my-app。但在浏览器中,路由器仍然会将 URL 视为 /my-app。在这种情况下,你应该使用条件编译来条件性地设置 base 属性:

If you are using a reverse proxy, it’s likely that your server will think it’s serving / when it is actually serving /my-app. But in the browser, the router will still see the URL as /my-app. In this situation, you should set the base prop conditionally using conditional compilation:

let base = if cfg!(feature = "hydrate") {
    "/my-app"
} else {
    "/"
};
// ...
<Router base> // ...

更新 <HydrationScripts root/>

Update the <HydrationScripts root/>

如果你正在使用服务端渲染,<HydrationScripts/> 组件负责加载用于应用水合(hydrate)的 JS/WASM。它有自己的 root 属性,用于指定水合脚本的基础路径。如果这些脚本也是从子目录提供的,你应该将该基础路径包含在 root 属性中。

If you’re using server rendering, the <HydrationScripts/> component is responsible for loading the JS/WASM to hydrate the app. This has its own root prop that specifies the base path for the hydration scripts. If they are also being served from a subdirectory, you should include that base path as the root prop.

更新服务器函数 URL

Update the Server Function URL

如果你正在使用服务器函数,它们默认会向 / 发送请求。如果你的服务器函数处理器挂载在不同的路径,你可以使用 set_server_url 来设置。

If you are using server functions, they will default to sending requests to /. If your server function handler is mounted at a different path, you can set that with set_server_url.

Trunk 配置

Trunk configuration

如果你正在使用 Trunk 进行客户端渲染,请查阅 Trunk 文档以了解如何通过 --public-url 设置公共 URL。

If you’re using client-side rendering with Trunk, consult the Trunk docs on how to set the public URL via --public-url.