Laravel 11部署到服务器后导航栏链接失效,仅首页可用
解决Laravel 11部署后仅首页可访问的方案
以下是针对部署后非首页链接返回404错误的具体解决步骤:
1. 确认服务器根目录指向public文件夹
将网站的根目录设置为项目的public目录,而非项目根目录。比如:
- Apache虚拟主机配置中,
DocumentRoot需指向/var/www/your-project/public - Nginx配置中,
root参数需指向/var/www/your-project/public
2. 配置Apache URL重写规则
- 先开启mod_rewrite模块:
a2enmod rewrite systemctl restart apache2 - 在项目
public目录下创建或修改.htaccess文件,写入以下内容:<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # 处理Authorization头 RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # 移除URL末尾斜杠 RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # 将所有请求转发到index.php RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule>
3. 配置Nginx URL重写规则
在Nginx的server配置块中添加以下规则:
location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { fastcgi_pass unix:/run/php/php8.2-fpm.sock; # 根据实际PHP版本调整路径 fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; include fastcgi_params; }
修改后重启Nginx:
systemctl restart nginx
4. 清除Laravel路由与配置缓存
进入项目根目录,执行以下命令清除缓存:
php artisan route:clear php artisan config:clear
5. 检查目录权限
确保服务器用户(如www-data)对storage和bootstrap/cache目录有读写权限:
chown -R www-data:www-data storage bootstrap/cache chmod -R 775 storage bootstrap/cache
内容的提问来源于stack exchange,提问作者Mahmoud
相关产品推荐
相关产品推荐

