新手求助:如何在子域名子文件夹部署Laravel项目(不用.htaccess)
Laravel部署在子域名子文件夹的非.htaccess方案
目录结构确认
你的服务器目录结构应为:
subdomain.com(子域名根目录)public_html(WordPress运行目录,子域名默认指向此处)subfolder(Laravel项目根目录,包含app、public、vendor等核心文件夹)
Laravel内部配置调整
更新.env文件
除了APP_URL,还需指定ASSET_URL确保静态资源路径正确:APP_URL=https://subdomain.com/subfolder ASSET_URL=https://subdomain.com/subfolder/public验证public/index.php路径
打开public_html/subfolder/public/index.php,确认以下两行路径正确(默认即为正确路径,因Laravel项目根目录在subfolder下):require __DIR__.'/../vendor/autoload.php'; $app = require_once __DIR__.'/../bootstrap/app.php';
服务器配置(核心方案)
1. Apache(虚拟主机配置)
找到子域名的虚拟主机配置文件(通常在/etc/apache2/sites-available/),添加或修改以下规则:
<VirtualHost *:443> ServerName subdomain.com DocumentRoot /path/to/public_html # WordPress默认请求处理 <Directory /path/to/public_html> AllowOverride None Require all granted DirectoryIndex index.php index.html </Directory> # Laravel请求转发:将/subfolder指向其public目录 Alias /subfolder /path/to/public_html/subfolder/public <Directory /path/to/public_html/subfolder/public> AllowOverride None Require all granted RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.php [L] </Directory> # 此处添加你的SSL证书配置 ssl_certificate /path/to/your/cert.pem; ssl_certificate_key /path/to/your/key.pem; </VirtualHost>
重启Apache生效:
sudo systemctl restart apache2
2. Nginx(站点配置)
找到子域名的Nginx配置文件(通常在/etc/nginx/sites-available/),修改为:
server { listen 443 ssl; server_name subdomain.com; root /path/to/public_html; index index.php index.html; # WordPress路由规则 location / { try_files $uri $uri/ /index.php?$args; } # Laravel路由规则:处理/subfolder请求 location /subfolder { alias /path/to/public_html/subfolder/public; try_files $uri $uri/ @laravel; location ~ \.php$ { fastcgi_pass unix:/run/php/php8.1-fpm.sock; # 替换为你的PHP-FPM路径 fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $request_filename; include fastcgi_params; } } location @laravel { rewrite /subfolder/(.*)$ /subfolder/index.php?$1 last; } # SSL证书配置 ssl_certificate /path/to/your/cert.pem; ssl_certificate_key /path/to/your/key.pem; }
重启Nginx生效:
sudo systemctl restart nginx
最后检查
- 路由使用Laravel内置辅助函数:
route('路由名称')或url('路径'),避免硬写绝对路径 - 静态资源使用
asset('资源路径')或mix('资源路径'),确保资源正确加载
内容的提问来源于stack exchange,提问作者Haydra gndy
相关产品推荐
相关产品推荐

