Linux下Nginx多域名Laravel应用登录重定向循环问题
解决Laravel多租户子域登录重定向循环问题
在Ubuntu上搭建Laravel多租户开发环境,主域maindomain.test登录后跳转到用户专属子域user.app.test,但子域无法识别登录状态,跳转回登录页;而主域能识别已登录凭据,又跳回子域,形成循环。Nginx/Valet Linux环境均出现该问题,同事机器运行正常,无错误日志。
配置信息
Nginx配置(/etc/nginx/sites-available/application)
server { listen 80; server_name maindomain.test; root /path/to/app/public; #example path index index.php index.html; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php8.2-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location ~ /\.ht { deny all; } } server { listen 80; server_name *.app.test; root /path/to/app/public; #example path index index.php index.html; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php8.2-fpm.sock; # adjust if using different version fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location ~ /\.ht { deny all; } }
Hosts配置(/etc/hosts)
127.0.0.1 maindomain.test 127.0.0.1 user.app.test
解决方案
问题核心是Cookie域未配置为共享父域,导致子域无法读取主域设置的登录SESSION Cookie。
- 修改Laravel环境变量配置
打开项目根目录下的.env文件,调整以下参数:
# 设为所有.test子域都能共享Cookie的父域,注意开头的点 SESSION_DOMAIN=.test # 开发环境禁用HTTPS Cookie,否则HTTP请求不会携带Cookie SESSION_SECURE_COOKIE=false
清除配置缓存与浏览器Cookie
- 执行Laravel缓存清除命令:
php artisan config:clear php artisan cache:clear php artisan route:clear- 打开浏览器,清除
maindomain.test和user.app.test域名下的所有Cookie,避免旧Cookie干扰。
验证Nginx配置(可选)
确保Nginx的PHP location块中传递正确的Host头,可手动添加或确认:
fastcgi_param HTTP_HOST $host;
修改后重启Nginx:
sudo systemctl restart nginx
补充说明
同事机器正常的原因大概率是其.env中已正确设置SESSION_DOMAIN为共享父域,或者开发环境(如Valet)自动配置了Cookie共享规则。
内容的提问来源于stack exchange,提问作者anas ali
相关产品推荐
相关产品推荐

