To force HTTPS in a Laravel application, you have several options depending on your Laravel version and server configuration:
Create a middleware to force HTTPS:
php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
class ForceHttps
{
public function handle($request, Closure $next)
{
if (!$request->secure() && App::environment('production')) {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
Then register it in app/Http/Kernel.php
:
php
protected $middleware = [
// ...
\App\Http\Middleware\ForceHttps::class,
];
In AppServiceProvider.php
:
php
public function boot()
{
if (config('app.env') === 'production') {
\URL::forceScheme('https');
}
}
Add this to your .htaccess
file in the public folder:
apache
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
Add this to your Nginx server block:
nginx
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
If you're behind a load balancer, configure trusted proxies in AppServiceProvider
:
php
public function boot()
{
if (config('app.env') === 'production') {
\URL::forceScheme('https');
$this->app['request']->server->set('HTTPS', true);
}
}
Choose the method that best fits your server setup. The middleware approach is generally the most flexible as it works across different server environments. https://www.cloudmailstore.com/hosting.php