Updated June 2026. Tested on Laravel 13 and PHP 8.4.

For SEO and consistency you want every visitor on one canonical address: HTTPS, and one of www or the bare domain, not both. Serving the same page on http, https, www and non www splits your ranking and confuses caching. Here is how to force a single canonical URL with a 301 redirect, and a note on where this work really belongs.

A redirect middleware

Create a middleware that pushes visitors to HTTPS and your chosen host. This version redirects to the bare domain (drop the www); flip the check if you prefer www.

php artisan make:middleware CanonicalDomain
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CanonicalDomain
{
    public function handle(Request $request, Closure $next)
    {
        if (app()->environment('production')) {
            $host = $request->getHost();

            $wantsRedirect = ! $request->secure() || str_starts_with($host, 'www.');

            if ($wantsRedirect) {
                $target = 'https://'.preg_replace('/^www\./', '', $host).$request->getRequestUri();

                return redirect()->to($target, 301);
            }
        }

        return $next($request);
    }
}

It only acts in production, so local development over plain HTTP keeps working. A 301 is the right status here because the move is permanent, which tells search engines to pass ranking to the canonical URL.

Register it

In current Laravel, add it to the web group in bootstrap/app.php.

->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        \App\Http\Middleware\CanonicalDomain::class,
    ]);
})

Forcing the scheme on generated links

Redirecting requests is one half. You also want the URLs Laravel generates to use HTTPS. Force the scheme in a service provider's boot.

use Illuminate\Support\Facades\URL;

if (app()->environment('production')) {
    URL::forceScheme('https');
}

The better place: your web server

Worth saying plainly: the cleanest place to do this is usually the web server, not the app. It is faster, because the redirect happens before PHP runs, and it keeps the concern out of your code. With Caddy, HTTPS is automatic, and a www to bare domain redirect is a two line block.

www.techalyst.com {
    redir https://techalyst.com{uri} permanent
}

Use the Laravel middleware when you cannot change the web server config, for example on shared hosting. When you control the server, prefer doing it there. Either way the goal is the same: one canonical, secure URL for every page. Questions welcome in the comments.