Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Set asset without protocol

Use asset helper function like below:

<script src="{{ asset('/assets/js/jquery-2.1.1.min.js') }}"></script>

will get

<script src="http://xxx.xxx.com/assets/js/jquery-2.1.1.min.js"></script>

Is there any laravel build-in solutions can let it be

<script src="//xxx.xxx.com/assets/js/jquery-2.1.1.min.js"></script>

and properly display with http and https protocols?

[EDIT]

I know that Laravel normally detects the protocol correctly, but when behind a load balancer, it does not. So I'm still looking for a solution to this.

like image 243
Chen-Tsu Lin Avatar asked Dec 19 '14 09:12

Chen-Tsu Lin


2 Answers

Laravel create secured link only if the request is considered as secured.

Laravel has already a way to treat non httpS traffic as "secured" if it's comming from a "trusted proxies".

You can declare such trusted proxies in your application service provider like that:

 Request::setTrustedProxies(array( '199.27.128.0/21', 'some other range'));

Also, make sure your loadbalancer set the following headers correctly:

Host, X-Forwarded-Host, X-Forwarded-Port, X-Real-IP, X-Forwarded-For and X-Forwarded-Proto

"Public" proxies such as cloudflare already does this btw.

Basically the point here is that client connection is terminated at one of the frontend servers (acting as a proxy), thus we have to declare communication from that server as trusted so that laravel use headers from the proxy server instead of the values readed localy.

Doing this enable functions such as Request::isSecure() or Request::ip() to return a consistent result.

like image 157
Atrakeur Avatar answered Oct 10 '22 11:10

Atrakeur


Laravel will automaticly change the url of the asset to the protocol used to load the site.

If your site is loaded over a secure connection, the asset links will automaticly use https.

Update:

If you do want to display the assets with only //, you could write your own HTML macro.

like image 40
Jerodev Avatar answered Oct 10 '22 10:10

Jerodev