Laravel redirect externally using http or https in the url

Published

I have a domain: www.example.com

My Laravel 8 Production Project is setup to "force" SSL on the URL.
I have set this up as follows:

public/.htaccess

#SSL force
    RewriteEngine On 
    RewriteCond %{HTTPS} !on 
    RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

and

app/Providers/AppServiceProvider

public function boot()
    {
        if($this->app->environment('production')) {
            URL::forceScheme('https');
        }

    }

my .env file

APP_NAME=NameOfApp
APP_ENV=production
APP_KEY=*hidden*
APP_DEBUG=false
APP_URL=https://example.com

Everything works well. I have been using this code for months and never have any issues forcing SSL.

Now here is where I am stuck today, I need
example.com/redirect-me
to immediately redirect to
google.com
regardless if it is typed
http://example.com/redirect-me
or
https://example.com/redirect-me

In theory, all I have to do is create my redirect route inside web.php

Route::get('/redirect-me', function () {
    return redirect('https://www.google.com');
});

Now, here is where it gets tricky.
If I try to access
https://example.com/redirect-me
It works just fine, it sends me to google.com

But if I remove the https and use http only it will send me to this exact address: https://example.com/index.php
(It forces SSL correctly but sends me to the same domain along displaying index.php in the URL, kind of strange because I am not using any route with index.php)

I have emptied the browser cache, I have tried incognito mode, different devices, it still behaves this way.

How can I redirect to external domain correctly regardless if the user typed http or https for my Laravel 8 project?

Thanks in advance.

Source: Laravel

Published
Categorised as laravel, laravel-8, redirect, ssl, url-shortener Tagged , , , ,

Answers

Leave a Reply

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq