添加尾部斜杠时,Laravel 在 URL 中恢复为 /public/

问题描述 投票:0回答:2

这是我的根目录中的

.htaccess
,应该从 URL 中删除“public”:

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

这是我在公共目录中的

.htaccess
,应该去掉尾部斜杠:

<IfModule mod_rewrite.c>
    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]
</IfModule>

这一切都很好,除了当我输入带有尾部斜杠的 URL 时,它会重定向回不带尾部斜杠的 URL,而且还添加了

/public

例如我们有这条路线:

Route::get('/de', 'HomeController@index')->name('home');

通常,URL 看起来像domain.com/de。

但是,如果我在浏览器中输入

domain.com/de/
,它会重定向到
domain.com/public/de
而不是
domain.com/de
- 并且页面会正常加载。

我该如何解决这个问题?

php laravel .htaccess mod-rewrite
2个回答
4
投票

您的网站根目录.htaccess应该是这样的:

RewriteEngine On

# remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301,NE]

# route all requests to public/
RewriteRule ^(.*)$ public/$1 [L]

然后里面

public/.htaccess
有这个代码:

RewriteEngine On

# if /public/ is part of original URL then remove it
RewriteCond %{THE_REQUEST} /public/(\S*) [NC]
RewriteRule ^ /%1 [L,NE,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

在测试此更改之前,请确保完全清除浏览器缓存。


0
投票

Apache/Nginx 应该指向 public 目录而不是 项目根目录

这样您就不需要添加任何 .htaccess 规则来删除 URL 中的“public”字符串

© www.soinside.com 2019 - 2024. All rights reserved.