[英]htaccess redirect domain to https, subdomain to http and www to non-www
[英]Redirect Http and www subdomain traffic to https automatically
我在.htaccess
上使用以下代碼將http
和www
流量重定向到https
。 我在Laravel
項目中使用了htaccess配置。
我面臨的問題是,當我在本地工作時,它將我重定向到.local
域上的https
。 由於無法在本地配置https,因此會出現問題。
因此,在本地,生產等多個環境中,將http
和www
重定向到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.