简体   繁体   中英

Really force http to https in Laravel

I have this Laravel App which I'm deplying to Heroku. I have followed all of the steps until I encountered a problem relating some assets (asset('css/app.css'), for example) refering to http urls, instead of https urls.

I solved that by adding

if(config('app.env')==='production'){
            \URL::forceScheme('https');
}

in the boot method of my AppServiceProvider.php file, and it worked.

But now I have encountered another http related problem that the previous code couldn't solve.

I am fetching my data using simplePaginate() function like so

    public function index(Question $question){
        $answers = $question->answers()->with('user');
        return  $answers->simplePaginate(3);
    }

This code returns me a response with my 3 answers, as well as with a property called 'next_page_url' which is, still, plain http (not https as i need it to be).

What can I do for this to be https as Heroku requires? 在这里你可以看到 http 中的 next_page_url 属性

The correct way is to change the URL of your app to https://example.com in the configuration file (.env file as an example). Just write APP_URL= https://example.com

But , when you use Heroku - their balancers can route your requests to https://yourDomain.com to your application over HTTP. So, the Laravel app receives the request to http://yourDomain.com and decides that you need a response with HTTP links.

As @seejayoz said you need to configure trusted proxies list for your app .

Heroku's load balancing setup means the indication of whether the request is HTTP or HTTPS comes from the X-Forwarded-Proto header. (Laravel also needs the X-Forwarded-For header to get the users' real IP addresses, incidentally.)

By default, Laravel doesn't trust these headers (as in a different setup it might come from a malicious client), so none of the requests will be detected as HTTPS. You can fix this by configuring the Laravel trusted proxy to trust the header.

In the default config, just setting $proxies = '*', will do the trick, and is safe on Heroku because the load balancers can't be bypassed by end users.

I think you can use withPath (or setPath alias) :

$pagi=$answers->simplePaginate(3); 
$pagi->withPath("https://link/xxx/"); 
return $pagi; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM