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

如何用.htaccess移除Laravel共享主机URL中的/public/路径

移除Laravel网站URL中的/public/部分

一、共享主机上的.htaccess修改

替换你当前根目录下的.htaccess内容为以下规则:

RewriteEngine On

# 将所有非/public/开头的请求转发到public目录
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L]

这个规则会自动把website.local/xxx的请求映射到website.local/public/xxx,但URL栏不会显示/public/。

二、本地主机的配置调整

本地修改后是可见的,需要根据你使用的Web服务器调整配置:

  • Apache:修改虚拟主机配置文件,将DocumentRoot指向Laravel项目的public目录:

    <VirtualHost *:80>
        ServerName website.local
        DocumentRoot "/你的项目路径/laravel-project/public"
        <Directory "/你的项目路径/laravel-project/public">
            AllowOverride All
            Require all granted
        </Directory>
    </VirtualHost>
    

    修改后重启Apache,访问website.local就不会带/public/。

  • Nginx:在站点配置中设置root为项目的public目录:

    server {
        listen 80;
        server_name website.local;
        root /你的项目路径/laravel-project/public;
    
        index index.php index.html index.htm;
    
        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }
    
        location ~ \.php$ {
            fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; # 替换为你的PHP-FPM路径
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
            include fastcgi_params;
        }
    }
    

    重启Nginx后即可生效。

额外注意

  1. 确保Laravel项目根目录下的.env文件中,APP_URL设置为http://website.local(不要带/public),避免框架生成的链接自动带上/public。
  2. 如果共享主机不支持上述Rewrite规则,联系主机商确认是否有特殊的目录配置限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 18:53:22