Home > Back-end >  Preventing http access in Laravel 8
Preventing http access in Laravel 8

Time:11-29

I have a question about force using HTTPS in laravel, i've added a condition inside AppServiceProvider.php, creating a middleware and modifying the .htaccess file. But I can still access the http page. Is there any other way to get laravel to redirect to https instead of http, and how to prevent user to acces the http addres? thank you!

my .htaccess :

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L,QSA]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

AppServiceProvider.php :

public function boot()
{
    if (env('APP_ENV') === 'production') {
        $this->app['request']->server->set('HTTPS','on'); // this line

        URL::forceSchema('https');
    }
}

HttpsProtocolMiddleware :

public function handle(Request $request, Closure $next)
{
    if (!$request->secure() && app()->environment('production')) {
        return redirect()->secure($request->getRequestUri());
    }
    
    return $next($request);
}

CodePudding user response:

add this at the top of your .htaccess file

RewriteEngine On 
RewriteCond %{HTTPS} off 
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  • Related