DEV Community

Akshay Joshi
Akshay Joshi

Posted on

๐Ÿ”’ Stop the Mix-Up! How to Force HTTPS in Laravel and Fix Your AJAX Woes

If your Laravel app runs on HTTPS, but AJAX calls or asset URLs still sneak out as http://, you're not alone. This invisible bug can silently break your front-end, trigger mixed content warnings, or even kill your SEO.

Letโ€™s fix that once and for all โ€” the Laravel way. ๐Ÿ› ๏ธ


๐Ÿงจ The Problem

You've deployed your Laravel app to production with a valid SSL certificate. Your APP_URL is set to:

APP_URL=https://mydomain.com
Enter fullscreen mode Exit fullscreen mode

But Laravel still generates http:// links. Why?

Because Laravel doesnโ€™t just trust the APP_URL. It decides whether to generate https:// based on request()->isSecure() โ€” which often returns false behind Cloudflare, Nginx, or load balancers unless properly configured.

Result: your url('/some-path') outputs http://mydomain.com/some-path โ€” triggering mixed content issues.


โœ… The Fix: Force HTTPS in Laravel

๐Ÿ”ง Step 1: Update AppServiceProvider

Open app/Providers/AppServiceProvider.php and modify the boot() method:

use Illuminate\Support\Facades\URL;

public function boot()
{
    if (app()->environment('production')) {
        URL::forceScheme('https');
    }
}
Enter fullscreen mode Exit fullscreen mode

This forces all generated URLs in production to use HTTPS โ€” regardless of what Laravel thinks the request is.


๐Ÿ›ก๏ธ Step 2: Trust Proxy Headers

If your app runs behind Cloudflare or a reverse proxy (most do), Laravel needs to trust forwarded headers.

Update app/Http/Middleware/TrustProxies.php:

protected $proxies = '*'; // or specify IPs for more control

protected $headers = \Illuminate\Http\Request::HEADER_X_FORWARDED_ALL;
Enter fullscreen mode Exit fullscreen mode

This ensures Laravel correctly detects HTTPS requests from proxies/load balancers.


โ™ป๏ธ Step 3: Clear Cache (Always)

php artisan config:clear
php artisan cache:clear
Enter fullscreen mode Exit fullscreen mode

Otherwise, you may still get stale http:// responses.


๐Ÿ’ก Bonus Tip: Don't Trust APP_URL Alone

The .env setting APP_URL is used by:

  • php artisan route:cache
  • Email and notification generation
  • Asset helpers in some cases

But it does not affect URL generation in runtime requests โ€” only the actual request scheme matters.


๐Ÿ‘€ Final Result

  • All calls to url(), route(), and even asset helpers will return https:// URLs.
  • No more mixed content.
  • AJAX behaves like it should.
  • Your SEO and frontend sanity are saved.

๐Ÿ’ฌ TL;DR

Laravel doesnโ€™t know your site is HTTPS unless you force it and trust the proxy. Add this to your AppServiceProvider, and you're golden.

if (app()->environment('production')) {
    URL::forceScheme('https');
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ฌ Have you been bitten by the http in disguise? Share your fix or setup below!

Top comments (0)