PAYATHON 2026

Svelte routing:页面与同名目录如何处理?

数据小陈

结论

SvelteKit 的路由层允许 src/routes/posts/+page.svelte 和 src/routes/posts/post_title1/+page.svelte 同时存在。直接访问 /posts 失败时,通常不必先怀疑 Svelte 路由冲突。更常见的问题在静态部署层:Apache 把 /posts 当成物理目录,或者 .htaccess 把无扩展名 URL 改写成了不存在的 .html。处理时,要让 /posts 先命中 posts.html,同时删掉会把子路径拦走的 /posts/... -> /post/... 旧重定向。

原因

  1. SvelteKit 通过客户端导航切换页面时,不会向服务器请求对应的 HTML。页面内跳转正常,并不代表直接访问或刷新 URL 也正常。
  2. 用 adapter-static 且 trailingSlash 设为 never 时,构建结果常常像这样:
build/
├── posts.html
└── posts/
    ├── post_title1.html
    └── post_title2.html

此时 posts.html 和 posts/ 目录会同时存在。Apache 的 DirectorySlash、DirectoryIndex 和 RewriteRule 有可能先处理目录。 3. 原来的 RewriteCond %{REQUEST_FILENAME} !-f 只排除了真实文件,没有排除目录。如果 /posts 落到目录上,而 posts.html 又没被正确命中,就会返回 404。 4. RedirectMatch 301 \"^/posts/(.+)$\" \"/post/$1\" 会把所有 /posts/post_title 跳到 /post/post_title,这种规则要删掉或改写。

推荐方案:保持无尾部斜杠,优先匹配同名 .html

先确认构建输出。如果 /posts 对应的是 posts.html,就在站点根目录的 .htaccess 中使用下面规则:

DirectoryIndex index.html
DirectorySlash Off
Options -Indexes

RewriteEngine On

# 1. 真实文件直接返回
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# 2. 无扩展名路径优先匹配同名 .html
#    这样 /posts 会命中 posts.html,而不是 posts/ 目录
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+?)/?$ $1.html [L]

# 3. 确实要访问目录时,使用目录下的 index.html
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME}/index.html -f
RewriteRule ^(.*)$ $1/index.html [L]

# 4. 去掉文件型路由的尾部斜杠
RewriteCond %{REQUEST_URI} /$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)/$ /$1 [R=301,L]

# 不要保留下面这类旧规则,否则 /posts/post_title 会被重定向走
# RedirectMatch 301 ^/posts/(.+)$ /post/$1

SvelteKit 这边要统一 trailingSlash,比如在 src/routes/+layout.js 里写成:

export const prerender = true;
export const trailingSlash = 'never';

同时确认静态适配器能正常输出。svelte.config.js 可以参考下面这样:

import adapter from '@sveltejs/adapter-static';

/** @type {import('@sveltejs/kit').Config} */
const config = {
  kit: {
    adapter: adapter({
      pages: 'build',
      assets: 'build',
      fallback: undefined,
      precompress: false,
      strict: true
    })
  }
};

export default config;

备选方案:使用尾部斜杠,避开文件与目录同名歧义

如果 URL 允许带尾部斜杠,可以设置:

// src/routes/+layout.js
export const prerender = true;
export const trailingSlash = 'always';

构建输出会变成 posts/index.html、posts/post_title1/index.html。这时 Apache 只需要 DirectoryIndex,不要再做 .html 重写:

DirectoryIndex index.html
Options -Indexes

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^(.*)$ /$1/ [R=301,L]

这样 /posts/ 和 /posts/post_title/ 都由目录里的 index.html 提供,冲突最少,代价是 URL 会多一个尾部斜杠。

注意事项

  • 改完后直接访问 /posts 和 /posts/post_title1,不要只点站内链接测试。
  • 如果构建输出是 posts/index.html 而不是 posts.html,就别用规则 2,改用目录索引,或者把 trailingSlash 设为 'always'。
  • DirectorySlash Off 要和 Options -Indexes 一起用,避免目录列表被直接暴露。
  • 针对 /posts 的 RedirectMatch 和 RewriteRule 不要混着留好几条,不然排查顺序会很麻烦。
  • 改完 .htaccess 后清一下浏览器缓存,或者用无痕窗口验证,避免 301 缓存干扰。

备注:内容仅供参考。