Laravel 7 -如何从我的应用程序中删除尾随的斜杠URL?

pbgvytdp  于 2023-10-22  发布在  其他
关注(0)|答案(2)|浏览(108)

我已经尝试过更改.htaccess文件,尝试了几种解决方案,没有任何效果。每当我在URL中添加一个尾随斜杠时,它会打开另一个页面,这不应该发生,在URL中添加一个尾随斜杠应该将其重定向到没有尾随斜杠的URL。我尝试了以下解决方案:
Solution 1
Solution 2
我想实现的是,对于我应用程序中的每个URL,http://127.0.0.1:8080/login/都应该重定向到http://127.0.0.1:8080/login

public/.htaccess

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

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [R=301,L]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

// Navigation Menu
Route::get('advisor', 'AdvisorController@index');
Route::get('investment', 'InvestmentController@index');
Route::get('investor', 'InvestorController@index');
Route::get('product', 'ProductController@index');
Route::get('rate', 'RateController@index');
//  Stop registration other functions
 Auth::routes([
    'register' => false, // Registration Routes...
    'reset' => false, // Password Reset Routes...
    'verify' => false, // Email Verification Routes...
  ]);
// Login
Route::get('/', function () { 
  return redirect('login');
});
// Dashboard
Route::get('/home', 'HomeController@index')->name('home');
//admin users
Route::resource('/admin/users', 'Admin\UsersController', ['except' => ['show', 'create', 'store']]);

错误截图:

没有尾随斜杠,我的应用程序URL:

现在,如果我在URL后面加上一个斜杠,我会得到这样的结果:

nqwrtyyt

nqwrtyyt1#

最后,我能够用中间件来做这件事,编辑.htaccess不知何故在本地不起作用,或者它在我的应用程序中不起作用,无论如何,检查下面的解决方案:

if (preg_match('/.+\/$/', $request->getRequestUri()))
 {
    return Redirect::to(rtrim($request->getRequestUri(), '/'), 301);
 }

参考here

gupuwyp2

gupuwyp22#

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class RedirectTrailingSlash
{
    /**
     * @param Request $request
     * @param Closure $next
     * @return mixed|void
     */
    public function handle(Request $request, Closure $next)
    {
        $pathInfo = $request->getPathInfo();
        if ($request->isMethod('get') && Str::endsWith($pathInfo, '/')) {
            $queryString = count($request->all()) ? '?'.http_build_query($request->all()) : '';
            return response('', 301)->header('Location', rtrim($pathInfo, '/') . $queryString);
        }

        return $next($request);
    }
}

相关问题