How to Redirect www to non-www URLs in Laravel

AuthorSumit Dey Sarkar

Pubish Date04 Feb 2024

categoryLaravel

In this tutorial, we will learn how to redirect www to non-www URLs in Laravel.

How to Redirect www to non-www URLs in Laravel

Redirect www to non-www URLs in Laravel

To redirect www to non-www URLs in Laravel, you need to follow the below steps:

Step 1: Update .env File:

Open .env file of your project in the root directory of your Laravel project and make sure the APP_URL does not contain "www".

For example:

APP_URL=http://example.com

Step 2: Update RouteServiceProvider:

Open the app/Providers/RouteServiceProvider.php file, and inside the boot method, add a check for the www subdomain and redirect if necessary.

Add the following code:

use Illuminate\Support\Facades\URL;

public function boot()
{
    if (config('app.env') === 'production') {
        URL::forceScheme('https');
        $this->app['request']->server->set('HTTPS', true);
    }

    $this->configureRateLimiting();

    $this->routes(function () {
        Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace)
            ->group(base_path('routes/api.php'));

        Route::middleware('web')
            ->namespace($this->namespace)
            ->group(function () {
                if (request()->getHost() === 'www.example.com') {
                    // Redirect from www to non-www
                    Route::redirect('/', config('app.url'), 301);
                }

                require base_path('routes/web.php');
            });
    });
}

Replace 'www.example.com' with your actual www domain, and config('app.url') with your non-www domain.

Step 3: Clear Cache:

After above changes, you should clear the configuration cache by running the following command in your terminal:

php artisan config:cache

If you are in a production environment, you may also need to clear the route cache:

php artisan route:cache

If you are not in production, you may skip the route cache clearing step.

Step 4: Test:

Test the redirection by accessing your website with the www subdomain and verifying that it redirects to the non-www version.

These steps should help you redirect www to non-www URLs in Laravel.

Comments 0

Leave a comment