.htaccess Laravel自动将url从http重定向到https

.htaccess Laravel自动将url从http重定向到https,.htaccess,laravel,laravel-5.2,.htaccess,Laravel,Laravel 5.2,我想为我的Laravel应用程序自动从http重定向到https url是app1.domain.com 我已将以下几行添加到公用文件夹中的.htaccess文件中,但它似乎没有生效 RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] 当我键入http://app1.domain.com,url不会重定向,并保持在http上。当我通过http://app1.domain

我想为我的Laravel应用程序自动从http重定向到https

url是app1.domain.com

我已将以下几行添加到公用文件夹中的.htaccess文件中,但它似乎没有生效

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
当我键入
http://app1.domain.com
,url不会重定向,并保持在http上。当我通过
http://app1.domain.com/auth/login
,我有一个404。如果我手动将
https
添加到
https://app1.domain.com/auth/login
,然后它就可以工作了,但我希望它能自动重定向到
https

.htaccess

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Added those 2 lines for ssl redirect
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

</IfModule>
致:


服务器名www.app1.domain.com
ServerAlias app1.domain.com

重定向永久/https://app1.domain.com/ 我使用一个中间件函数,并将其应用于所有路由。然后,如果您需要为任何特定的url删除它

namespace App\Http\Middleware;

use Closure;

class HttpsProtocol {

public function handle($request, Closure $next)
{
        if (!$request->secure() && env('APP_ENV') === 'production') {
            return redirect()->secure($request->getRequestUri(), 301);
        }

        return $next($request); 
   }
}
然后添加到kernel.php文件中

    'https' => [
        'App\Http\Middleware\HttpsProtocol'   
    ],
然后像这样把这个钉在你的路线上

 Route::get('/', ['middleware' => array('web','https'),'uses' => 'HomeController@index']);
或者在全球范围内注册


将其放入.htaccess文件中

RewriteEngine On

# Redirect to https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

它对我起作用。

它在哪里托管,没有使用nginx,是吗?托管在vps上,使用ApacheOk,您已经
上重写了引擎?您是否检查过其他htaccess重定向是否有效。像301或类似的东西,看看是否有任何其他潜在的问题?是的,.htaccess文件已经存在,我只是添加了上面的两行。我“我会发帖的,在拉威尔以外的地方发帖不是更好的做法吗?您这样做是因为它不适合您使用.htaccess文件吗?实际上,在没有编写一系列条件的情况下,我确实很难让htaccess在所有情况下可靠地工作。您可能会争辩说htaccess更干净,但它们都在重定向请求,并且在laravel中这样做允许您在以后需要时扩展它。我相信这两种方法都有道理。但这很有效,而且更容易扩展。谢谢@severian的输入,我真的很感激。我找到了一个似乎可以正常工作的解决方案(使用web服务器将所有http请求重定向到https)。参见上面的解决方案
 Route::get('/', ['middleware' => array('web','https'),'uses' => 'HomeController@index']);
RewriteEngine On

# Redirect to https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]