自动将Http和www子域流量重定向到https

时间:2019-01-27 08:28:19

标签: .htaccess

我在.htaccess上使用了以下代码,将httpwww的流量重定向到https。我在我的Laravel项目中使用了htaccess配置。

我面临的问题是,当我在本地工作时,它会将我重定向到https域上的.local。由于无法在本地配置https,因此会出现问题。

那么在本地,生产等多个环境中,将httpwww重定向到https的推荐方法是什么。

<IfModule mod_rewrite.c>
    # Redirect everything to https
    RewriteEngine On
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} ^www\. [NC]
    RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
</IfModule>

3 个答案:

答案 0 :(得分:1)

RewriteCond是您的“如果条件”。只需在

之后添加
RewriteCond %{HTTPS} off [OR]
RewriteCond %{REMOTE_ADDR} !127.0.0.1
RewriteCond %{HTTP_HOST} !localhost

答案 1 :(得分:0)

app/Providers/AppServiceProvider.php中,您可以强制所有路由或资产链接到https:

if (config('app.env') === 'production') {
    URL::forceScheme('https');
}

然后创建一个中间件来强制所有请求保护请求的安全:

php artisan make:middleware SecureSite

SecureSite.php文件夹中打开app/Http/Middleware并覆盖handle()函数:

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

    return $next($request);
}

然后在app/Http/Kernel.php中将其首先添加到$middlewareGroups下的web中:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\SecureSite::class,
        ...

然后确保您的所有web.php路由都具有web中间件:

php artisan route:list

无需还原.htaccess,如果要还原,here是原始的.htaccess

答案 2 :(得分:0)

如下更新了.htaccess,它现在可以工作了。感谢您的帮助。

<IfModule mod_rewrite.c>
    # Redirect everything to https
    RewriteEngine On
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{REMOTE_ADDR} !127.0.0.1
    RewriteCond %{HTTP_HOST} !localhost
    RewriteCond %{HTTP_HOST} !\.local$
    RewriteCond %{HTTP_HOST} ^www\. [NC]
    RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
</IfModule>
相关问题