support@codebucket.net

How to Redirect www URL to Non-www URL

How to Redirect www URL to Non-www URL

K. M. Shawkat Zamil | December 21, 2022

Hello developers,

 

Today I will share a very important topic. Sometimes you see that google index your website's non-www URL in their system. After the indexing you want whenever a user types a www URL into the browser, you want to redirect to a non-www URL. There are several techniques I will share in today's lesson.

 

Process 1: Nginx Configuration

 

You can make a new configuration to your configuration directory in Nginx. Most of the cases the file is located in /etc/nginx/conf.d/ directory. You can make a file in that directory and paste the following code:

 

/etc/nginx/conf.d/redirect.conf

server {
    server_name www.robindirksen.com;
    return 301 $scheme://robindirksen.nl$request_uri;
}

 

This will redirect every www URL to a non-www URL. 

 

Process 2: Use the .htaccess file

 

In my perspective, the easy one is the .htaccess file utilization. Every project or any framework-oriented project has a .htaccess file. We can write the below code in the .htaccess file. After that put the file in the root of your project.

 

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
	
</IfModule>

 

Process 3: Using the Laravel Application

 

In the Laravel application, you can make a middleware and put it in the route block. The command to create middleware is given below: 

 

php artisan make:middleware RedirectToNonWwwMiddleware

 

Put the following code in the middleware, and use your domain name in place of "yourdomain.com".

 

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Redirect;

class RedirectToNonWwwMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (substr($request->header('host'), 0, 4) == 'www.') {
            $request->headers->set('host', 'yourdomain.com');

            return Redirect::to($request->path());
        }
        
        return $next($request);
    }
}

 

The middleware can be added to all the requests or only the web. To add it to the web group, you should add the line in the Kernel.php $middlewareGroups Block. Place the below code in the $middlewareGroups section.

 

app/Http/Kernel.php

'web' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,

    \App\Http\Middleware\RedirectToNonWwwMiddleware::class
],

 

Keep it in mind when you have links to static files (like images, CSS, or javascript) you have to enable .htaccess or nginx redirects, otherwise, those will be served from the www version. This happens because the static files won't boot the framework which means it doesn't receive the redirect.

 

Hope this might help you in the journey of development.

 

Read More: How to create Infinite Scroll Pagination using PHP and jQuery

 

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.