SvelteKit静态部署Apache2后page-two页面404,求缺失配置
解决方案
SvelteKit构建后的静态站点属于单页应用(SPA)范畴,Apache默认会尝试寻找对应URL的物理文件/目录,而SPA的路由是由前端JS处理的,因此需要配置URL重写,让所有不存在的文件/目录请求都转发到入口文件index.html。
步骤1:启用Apache重写模块
首先确保mod_rewrite模块已启用:
sudo a2enmod rewrite sudo systemctl restart apache2
步骤2:添加重写规则到站点配置
修改你的Apache站点配置,在<VirtualHost>块内添加以下规则:
ServerAdmin contact@example.com ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/project/build/ # 开启重写引擎 RewriteEngine On # 如果请求的文件或目录不存在,重定向到index.html RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.html [L] // Logging // SSL
可选:调整SvelteKit构建配置
如果你的项目使用adapter-static构建,可以在svelte.config.js中配置trailingSlash选项,适配Apache的URL解析习惯:
import adapter from '@sveltejs/adapter-static'; export default { kit: { adapter: adapter({ // 根据需求设置为'always'(强制带斜杠)或'never'(强制不带斜杠) trailingSlash: 'always' }) } };
最后验证
修改配置后重启Apache服务:
sudo systemctl restart apache2
此时直接访问/page-two应该就能正常加载页面了。
内容的提问来源于stack exchange,提问作者njk18
相关产品推荐
相关产品推荐

