How to redirect from :
https://www.example.com
http://www.example.com
http://example.com
to :
https://example.com
How can I do this with .htaccess
file?
How to redirect from :
https://www.example.com
http://www.example.com
http://example.com
to :
https://example.com
How can I do this with .htaccess
file?
you can do that by add this code to .htacces file
RewriteEngine on
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
note if you want remove www from url
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
Define a middleware for removing www from the url using below command php artisan make:middleware RedirectToNonWwwMiddleware
and write below code in handle method of that middleware
public function handle($request, Closure $next)
{
if (substr($request->header('host'), 0, 4) == 'www.') {
$request->headers->set('host', config('app.url'));
$trailing = $request->path() == '/' ? '' : '/';
return \Redirect::to(config('app.url') . $trailing . $request->path());
}
return $next($request);
}
Add the middleware to the array of $middleware
inside app\Http\Kernel.php
file like below
protected $middleware = [
// Other middlewares ...
\App\Http\Middleware\RedirectToNonWwwMiddleware::class,
];
Define the url inside your .env file with https like below
APP_URL=https://example.com
At last clear the config cache by running php artisan config:clear
.
I found the best answer to my question :
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
It supported all of positions that I said.
You can test it in : Test .htaccess
so you can redirect from :
https://www.example.com
http://www.example.com
http://example.com
to :
https://example.com
with that code.