【问题标题】:Laravel redirect from https:// to https://wwwLaravel 从 http:// 重定向到 https://www
【发布时间】:2018-07-23 16:01:09
【问题描述】:

我是 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文件或需要添加任何控制器。

【问题讨论】:

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


    【解决方案1】:

    你可以使用 htaccess ,不要忘记 stop php artisan serve 并再次运行然后执行 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]
    

    【讨论】:

    • 这是一个 apache 配置。和php artisan serve没有关系
    【解决方案2】:

    当涉及到从 http 重定向到 https 时,您还必须考虑用于 seo 目的的版本是 www 还是非 www 或两个版本,

    这是我在自己的项目中使用 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

    【讨论】:

      猜你喜欢
      • 2015-10-03
      • 2016-10-15
      • 2018-09-26
      • 2014-05-08
      • 2016-01-20
      • 1970-01-01
      • 1970-01-01
      • 2016-02-28
      • 2015-10-23
      相关资源
      最近更新 更多