Laravel从https://重定向到https:// www

时间:2018-07-23 05:32:52

标签: laravel .htaccess mod-rewrite laravel-5

我是laravel框架的新手,现在我正在使用laravel开发完全开发的网站。我无法将网站https://重定向到https://www。我将htaccess文件更改为

 <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>

还有

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

    </IfModule>

它基于.env文件或需要添加任何控制器。

2 个答案:

答案 0 :(得分:1)

当要从http重定向到https时,您还必须考虑使用www或非www的版本,或同时用于seo的两个版本,

这是我使用Laravel中间件在我自己的项目中处理它的方式,

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

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

答案 1 :(得分:0)

您可以使用htaccess,不要忘记停止php artisan服务并再次运行,然后执行 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]