簡體   English   中英

自動將Http和www子域流量重定向到https

[英]Redirect Http and www subdomain traffic to https automatically

我在.htaccess上使用以下代碼將httpwww流量重定向到https 我在Laravel項目中使用了htaccess配置。

我面臨的問題是,當我在本地工作時,它將我重定向到.local域上的https 由於無法在本地配置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>

RewriteCond是您的“如果條件”。 只需添加

RewriteCond %{HTTPS} off [OR]
RewriteCond %{REMOTE_ADDR} !127.0.0.1
RewriteCond %{HTTP_HOST} !localhost

app/Providers/AppServiceProvider.php您可以強制所有路由或資產鏈接到https:

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

然后創建一個中間件來強制所有請求保護請求的安全:

php artisan make:middleware SecureSite

app/Http/Middleware文件夾中打開SecureSite.php並覆蓋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中將其首先添加到web下的$middlewareGroups

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

然后確保所有的web.php路由都具有web中間件:

php artisan route:list

無需更改.htaccess ,如果要還原, 這里是原始的.htaccess

如下更新了.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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM