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

如何使用.htaccess不重定向修改Laravel应用的URL路径

解决Laravel URL重写问题:去掉/GLara/public前缀

我来帮你搞定这个URL重写的问题,核心就是让服务器把/repositories/{account_name}/{repository_name}的请求正确转发到Laravel的入口文件,而不是去根目录找不存在的repositories目录。下面分两种常用方案来说:

方案一:修改Apache虚拟主机(推荐,最干净)

这是Laravel官方推荐的部署方式,直接把网站根目录指向Laravel的public文件夹,从根源上避免路径问题:

  1. 找到Apache的虚拟主机配置文件(通常在/etc/apache2/sites-available/your-domain.conf或者httpd.conf中)
  2. 修改DocumentRoot和Directory路径,指向你的GLara/public目录:
<VirtualHost *:80>
    ServerName your-domain.com  # 替换成你的域名或服务器IP
    DocumentRoot /path/to/GLara/public  # 替换成实际的GLara/public绝对路径

    <Directory /path/to/GLara/public>
        AllowOverride All
        Require all granted
        Options -Indexes +FollowSymLinks
    </Directory>
</VirtualHost>
  1. 启用mod_rewrite模块(如果没开启的话):
# Ubuntu/Debian系统
sudo a2enmod rewrite
# CentOS/RHEL系统
sudo systemctl restart httpd
  1. 重启Apache服务:
# Ubuntu/Debian
sudo systemctl restart apache2
# CentOS/RHEL
sudo systemctl restart httpd
  1. 最后在Laravel的路由文件(routes/web.php或routes/api.php)里定义你的路由:
Route::get('/repositories/{account_name}/{repository_name}', [YourRepoController::class, 'getRepositoryInfo']);

这样访问/repositories/xxx/yyy就会直接命中Laravel的路由,再也不会出现404了。

方案二:用根目录的.htaccess转发请求(无法修改虚拟主机时用)

如果没法改虚拟主机配置,就在服务器的网站根目录(也就是GLara所在的上级目录)新建一个.htaccess文件,把请求转发到Laravel的入口:

<IfModule mod_rewrite.c>
    RewriteEngine On

    # 把所有/repositories开头的请求转发到GLara/public/index.php处理
    RewriteRule ^repositories/(.*)$ /GLara/public/index.php/$1 [L]
</IfModule>

同时要确保GLara/public目录下的.htaccess是Laravel默认配置(用来处理Laravel内部路由):

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # 静态资源直接返回,不存在的请求交给index.php处理
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

这样服务器收到/repositories/xxx/yyy的请求时,会自动转发到/GLara/public/index.php/repositories/xxx/yyy,由Laravel的路由系统处理,不会再因为找不到物理目录返回404。

注意事项

  • 确保mod_rewrite模块已经启用,否则.htaccess不会生效
  • 修改Laravel的.env文件,把APP_URL设置成你的域名/IP,比如APP_URL=http://your-domain.com,避免生成错误链接

内容的提问来源于stack exchange,提问作者Mateusz Wiśniewski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:40:59