Nginx子目录移除Laravel的index.php及同域名部署配置问题
我来帮你搞定这个同一域名下部署Vue静态站点和Laravel API的问题,还要去掉烦人的index.php,核心就是靠Web服务器的路由规则区分请求,下面一步步给你说清楚:
第一步:先确认你的文件结构
先对应你给出的目录,确保结构清晰:
/var/www/site/ ├── frontend/dist/ │ ├── index.html # Vue静态首页 │ └── another.html # 其他静态页面 └── backend/api/ ├── index.php # Laravel API入口 └── ... # Laravel其他核心文件
第二步:Nginx配置方案(最常用生产环境)
这是解决问题的关键,通过Nginx的路由规则,把非/api开头的请求交给Vue静态资源,/api开头的请求转发给Laravel,自动去掉index.php。
创建或修改你的Nginx站点配置文件(通常在/etc/nginx/sites-available/your-domain.conf),内容如下:
server { listen 80; server_name your-domain.com; # 替换成你的实际域名 root /var/www/site/frontend/dist; # 默认指向Vue静态目录 index index.html index.htm; # 处理Vue前端路由(支持history模式,刷新页面不404) location / { try_files $uri $uri/ /index.html; } # 专门处理API请求,转发到Laravel后端 location /api { root /var/www/site/backend/api; # 指向Laravel项目根目录 try_files $uri $uri/ /api/index.php?$query_string; # 自动跳过index.php # 处理PHP解析,这里要注意PHP-FPM的路径 location ~ \.php$ { fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; # 替换成你服务器的PHP-FPM路径,比如php7.4-fpm.sock fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } # 可选:开启HTTPS的话,加上SSL配置 # listen 443 ssl; # ssl_certificate /path/to/your/cert.pem; # ssl_certificate_key /path/to/your/key.pem; }
配置完后,测试Nginx语法是否正确:
sudo nginx -t
没问题就重启Nginx生效:
sudo systemctl restart nginx
第三步:Laravel后端配置调整
- 打开Laravel的
.env文件,确保APP_URL设置正确:APP_URL=https://your-domain.com/api - Laravel的
routes/api.php里的路由默认已经带/api前缀,所以直接写业务路由就行,比如:
这样访问Route::get('/user', function () { return response()->json(['name' => '测试用户']); });your-domain.com/api/user就能拿到响应,完全不需要加index.php。 - 最后给Laravel的核心目录设置正确权限,避免报错:
chmod -R 755 /var/www/site/backend/api/storage chmod -R 755 /var/www/site/backend/api/bootstrap/cache
第四步:如果用Apache服务器的方案
要是你用的是Apache,也可以通过.htaccess来实现:
- 前端目录(
/var/www/site/frontend/dist)的.htaccess,支持Vue路由:<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule> - Laravel目录(
/var/www/site/backend/api)的.htaccess,去掉index.php:<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /api/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /api/index.php [L] </IfModule> - 开启Apache的重写模块,重启服务:
sudo a2enmod rewrite sudo systemctl restart apache2
最后测试验证
- 访问域名根目录(
your-domain.com),应该能正常加载Vue的首页 - 访问
your-domain.com/another.html,能打开静态页面 - 访问API路径比如
your-domain.com/api/user,能拿到Laravel返回的JSON,URL里完全看不到index.php
内容的提问来源于stack exchange,提问作者JustJohn
相关产品推荐
相关产品推荐

