CodeIn House

  • Laravel
  • WordPress
  • jQuery
  • Javascript
  • Contact
Home   Laravel   How to Set Preferred Domain (www or non-www) Using Middlewar ...

How to Set Preferred Domain (www or non-www) Using Middleware in Laravel ?

September 9, 2018 by SNK

how to setup preferred domain using middleware in laravel

In this article we are going to learn how to set preferred domain (www or non-www) using middleware in laravel.

If you own a website google see’s website as two websites with www and the one with non www and doing this, may lead the content duplication issue while google is indexing your website.

Now a days google is also showing the website as unsecured if they are not using SSL. So i suggest you to quickly move your site to https. This tutorial will also help you to move your website to https, but that can be obtained by doing some tweaks inside .htaccess too.

If you want more information you can always visit google documentation to read more about how to structure your website.

Let’s get started

What are we going to do ?

  1. Create new file inside app/config called domain.php and set preferred domain protocol.
  2. Create new middleware called preferred domain and add it inside kernel.php in middleware array.
  3. Create new class Domain.php inside App directory and write some function to redirect user to user http or https based on preference.

Step 1 : Create New file Inside App/Config as domain.php and set preferred domain protocol

In this step we are just simply going to create one domain.php file inside app/config and make it return an array of http and https.

domain.php Inside App/Config Directory
PHP
1
2
3
4
5
6
<?php
 
return [
    'preferred' => '//',
    'protocol' => 'https://',
];

Step 2 : Creating middleware called PreferredDomain.php and Registering it to Kernel.php

Create new middleware by going to the terminal and type php artisan make:middleware PreferredDomain.

Open that middleware and inside public function handle and just above the return $next($request);  paste

PreferredDomain.php Middleware Class
PHP
1
2
3
if($prefDomain->diff()) {
     return redirect()->to($prefDomain->translated(), 301);
}

Now, you middleware class should look like this,

Preferred Domai Middleware Class
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
 
namespace App\Http\Middleware;
 
use Closure;
use App\Domain;
 
class PreferredDomain
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $prefDomain = new Domain($request);
 
        if ($prefDomain->diff()) {
            return redirect()->to($prefDomain->translated(), 301);
        }
        return $next($request);
    }
}

After that, register this middleware inside the kernel.php inside the protected $middleware [];

Register Inside Kernel.php
PHP
1
2
3
4
5
6
7
8
protected $middleware = [
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\PreferredDomain::class,
];

Step 3 : Create new Domain.php to Configure Redirect

Create new class inside App directory as Domain.php and add these code below.

Domain.php
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
namespace App;
 
use Illuminate\Http\Request;
 
class Domain
{
    const REDIRECT_HTTP = 'http://';
    const REDIRECT_HTTPS = 'https://';
 
    const REDIRECT_WWW = '//www.';
    const REDIRECT_NOWWW = '//';
 
    const REGEX_FILTER_WWW = '/(\/\/www\.|\/\/)/';
    const REGEX_FILTER_HTTPS = '/^(http:\/\/|https:\/\/)/';
 
    /**
     * @var \Illuminate\Http\Request
     */
    protected $request;
 
    /**
     * @var string
     */
    protected $translated;
 
    /**
     * @param \Illuminate\Http\Request $request
     */
    public function __construct(Request $request) {
        $this->request = $request;
    }
 
    /**
     * @return bool
     */
    public function isEqual(): bool {
        return $this->request->fullUrl() !== $this->translated();
    }
 
    public function diff(): bool {
        $this->translated = $this->translate();
 
        return $this->isEqual();
    }
 
    public function translated(): string {
        if (!$this->translated) {
            $this->translated = $this->translate();
        }
        return $this->translated;
    }
 
    public function translate(): string {
        $protocol = $this->getHttpProtocol();
        $filtered = preg_replace(self::REGEX_FILTER_HTTPS, $protocol, $this->request->fullUrl());
        return preg_replace(self::REGEX_FILTER_WWW, $this->getDomainPreference(), $filtered);
    }
 
    public function getHttpProtocol(): string {
        if (!$this->request->secure()) {
            return self::REDIRECT_HTTP;
        }
        return config('domain.protocol') ?? self::REDIRECT_HTTP;
    }
 
    public function getDomainPreference(): string {
        return config('domain.preferred') ?? self::REDIRECT_WWW; // If you want your site to be redirected to non www just use REDIRECT_NOWWW
    }
}

This is it, if you try to redirect to https://websitename.com then would be automatically redirect to https://www.websitename.com.

If you have any problem. Make sure to mention them via comments.

SHARE ON
Buffer

Enjoyed this article?

Like us on

Laravel laravel www and non-www set preferred domain in laravel

Avatar for SNK

About SNK

Hello Welcome to my Blog. I develop Websites Using Laravel Framwork & WordPress. Get Latest updates on Facebook | Twitter

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Get Connected !! With Us

TOP POSTS

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

TUTORIALS TILL DATE

  • September 2022 (6)
  • June 2021 (7)
  • October 2020 (5)
  • September 2020 (6)
  • September 2018 (14)
  • August 2018 (3)
  • July 2018 (4)
  • March 2018 (8)
  • February 2018 (5)
  • January 2018 (1)
  • December 2017 (2)
  • August 2017 (8)
  • May 2017 (1)
  • April 2017 (1)
  • March 2017 (4)
  • February 2017 (3)
  • January 2017 (4)

CATEGORIES

  • Angular (2)
  • CSS3 (3)
  • D3 (3)
  • HTML5 (7)
  • JAVA (11)
  • Javascript (20)
  • jQuery (8)
  • Laravel (35)
  • Others (3)
  • PHP (11)
  • Spring (2)
  • WordPress (10)

Top Categories

  • Angular
  • CSS3
  • D3
  • HTML5
  • JAVA
  • Javascript
  • jQuery
  • Laravel
  • Others
  • PHP
  • Spring
  • WordPress

Get in Touch

DMCA.com Protection Status

Recent Articles

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

© 2012-22 CodeIn House.  •  All Rights Reserved.