Laravel+Vite生产构建后自动重定向至/build路径问题求助
解决Laravel+Vite构建后根域名重定向到/build的问题
1. 检查Vue Router基础路径配置
如果项目使用Vue Router,确保路由的历史模式基础路径设置为根目录,避免强制跳转至/build:
// src/router/index.js 或对应路由文件 import { createRouter, createWebHistory } from 'vue-router' const router = createRouter({ history: createWebHistory('/'), // 必须设置为根路径 '/' routes: [/* 你的路由配置 */] })
2. 修正Vite的base配置
在vite.config.js中明确设置根路径,同时确保Blade模板使用正确的资源加载指令:
- 更新
vite.config.js:
export default defineConfig({ base: '/', // 新增此行,指定资源根路径为域名根目录 plugins: [/* 现有插件配置 */], resolve: [/* 现有别名配置 */] })
- Blade模板中使用
@vite指令加载资源,不要手动写/build路径:
<!-- resources/views/welcome.blade.php 或主视图文件 --> @vite(['src/main.ts'])
3. 排查Laravel路由与重定向规则
- 确保根路由(
/)返回正确的主视图,无强制重定向:
// routes/web.php Route::get('/', function () { return view('welcome'); // 返回你的应用主视图 });
- 检查全局中间件、路由组中是否存在
return redirect('/build')这类强制重定向代码,如有则删除或修改。
4. 修正服务器配置
Nginx配置
确保服务器根目录指向Laravel的public文件夹,且try_files规则正确:
server { listen 80; server_name abc.com; root /path/to/your/laravel/public; index index.php index.html index.htm; location / { try_files $uri $uri/ /index.php?$query_string; } # PHP处理配置(保留原有即可) location ~ \.php$ { fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; include fastcgi_params; } }
Apache配置
确保public/.htaccess为Laravel默认配置,无额外重定向至/build的规则:
<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Send Requests To Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule>
5. 清理缓存
执行以下命令清理Laravel缓存,同时清理浏览器缓存或使用无痕模式测试:
php artisan cache:clear php artisan config:clear php artisan route:clear
内容的提问来源于stack exchange,提问作者Asif Mushtaq
相关产品推荐
相关产品推荐

