Skip to content
Advertisement

Preventing http access in Laravel 8

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);
}

Advertisement

Answer

add this at the top of your .htaccess file

RewriteEngine On 
RewriteCond %{HTTPS} off 
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement