skip to Main Content

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?

3

Answers


  1. Chosen as BEST ANSWER

    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.


  2. 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]
    
    Login or Signup to reply.
  3. 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 appHttpKernel.php file like below

    protected $middleware = [
    
        // Other middlewares ...
    
        AppHttpMiddlewareRedirectToNonWwwMiddleware::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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search