Sukumar Chandran
Sukumar Chandran

Reputation: 3

Laravel redirect from https:// to https://www

I am new in laravel framework now i'm working fully developed website using laravel. i could't redirect website https:// into https://www. i changed htaccess file like

 <IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
    RewriteCond %{HTTPS}s ^on(s)|
    RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]               
    </IfModule>

And

 <IfModule mod_rewrite.c> 
    RewriteEngine on
    RewriteCond %{HTTPS} on
    RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]  

    </IfModule>

It's based on .env file or need to add any controller.

Upvotes: 0

Views: 872

Answers (2)

Mohamed Akram
Mohamed Akram

Reputation: 2117

when it comes to redirect from http to https, also you have to think the version whether www or non www or both version you are using for seo purposes,

here is How i handle it in my own projects using Laravel Middleware,

public function handle($request, Closure $next)
{
    if(config('app.env') == 'production'){

        $host = $request->header('host');
        if (substr($host, 0, 4) != 'www.') {
            if(!$request->secure()){
                $request->server->set('HTTPS', true);
            }
            $request->headers->set('host', 'www.'.$host);
            return Redirect::to($request->path(),301);
        }else{
            if(!$request->secure()){
                $request->server->set('HTTPS', true);
                return Redirect::to($request->path(),301);
            }
        }
    }

    return $next($request);
}

Reference : https://www.techalyst.com/links/read/120/laravel-middleware-301-redirect-from-http-to-https-or-non-www-to-www-site-redirect

Upvotes: 1

Abdi
Abdi

Reputation: 608

you can use htaccess , do not forget stop php artisan serve and again run that and do composer dumpautoload

RewriteEngine On
#we replace domain.com/$1 with %{SERVER_NAME}%{REQUEST_URI}.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*) https://www.%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

#here we dont use www as non www was already redirected to www.
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

Upvotes: 1

Related Questions