You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让子域名下子文件夹的Laravel项目无需/public路径运行

解决Laravel项目在子域名子文件夹下的URL路径问题

方案一:修改虚拟主机配置(推荐,权限充足时优先使用)

既然你拥有VPS全部权限,直接修改子域名的虚拟主机配置是最可靠的方式,完全不需要依赖.htaccess:

  1. 找到子域名对应的虚拟主机配置文件,常见路径:
    • Debian/Ubuntu:/etc/apache2/sites-available/subdomain.example.com.conf
    • CentOS/RHEL:/etc/httpd/conf.d/subdomain.example.com.conf
  2. 将DocumentRoot和<Directory>块的路径直接指向Laravel项目的public目录:
    DocumentRoot /var/www/public_html/subdomain/subfolder/public
    
    <Directory /var/www/public_html/subdomain/subfolder/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
    注意替换成你服务器上的实际路径。
  3. 重启Apache服务使配置生效:
    • Debian/Ubuntu:sudo systemctl restart apache2
    • CentOS/RHEL:sudo systemctl restart httpd

配置完成后,访问https://subdomain.example.com会直接指向Laravel的public目录,URL中不会出现任何多余路径。

方案二:用.htaccess内部重写(无法修改虚拟主机时使用)

你之前的.htaccess问题在于未指定subfolder路径,且规则触发了外部跳转导致URL显示/public。正确的配置需要放在子域名的根目录(public_html/subdomain/)中:

Options -MultiViews
RewriteEngine On

# 排除已指向public目录的请求,避免循环
RewriteCond %{REQUEST_URI} !^/subfolder/public/
# 内部重写所有请求到subfolder/public,不改变URL
RewriteRule ^(.*)$ /subfolder/public/$1 [L,QSA]

同时要确保子域名的虚拟主机配置中开启了AllowOverride All,否则.htaccess规则不会生效。

如果你使用的是Nginx服务器

修改子域名的Nginx配置文件(通常在/etc/nginx/sites-available/subdomain.example.com),将root指向Laravel的public目录:

server {
    listen 443 ssl;
    server_name subdomain.example.com;

    root /var/www/public_html/subdomain/subfolder/public;
    index index.php index.html;

    # SSL证书配置(根据你的实际证书路径调整)
    ssl_certificate /path/to/ssl/cert.pem;
    ssl_certificate_key /path/to/ssl/key.pem;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.2-fpm.sock; # 替换为你的PHP-FPM套接字路径
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

保存后重启Nginx:sudo systemctl restart nginx

内容的提问来源于stack exchange,提问作者mm1234

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 23:30:06