An easy redirect to https for Laravel.
The fastest and easiest way to do a redirect is to configure the server to redirect requests itself (an example is shown below). But in some situations you may not have access to the configuration, or you need to do additional checks using PHP. Then this package comes in handy.
Add to .htaccess
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
Header always set Content-Security-Policy "upgrade-insecure-requests;"
You need to migrate configurations from port 80 to 443 and then add redirect from port 80 to port 443
server {
listen 443 ssl http2;
server_name my-domain.example www.my-domain.example;
# ... configuration
}
server {
listen 80;
server_name my-domain.example www.my-domain.example;
return 301 https://my-domain.example$request_uri;
}
For use php < 8.0 please use version "^2.0"
composer require yaroslawww/laravel-force-https
Moreover, this package includes a middleware object to redirect all "non-ssl" routes to the corresponding "ssl".
So, if a user navigates to http://url-to-laravel/test and the system has this middleware active it would redirect (301) him automatically to https://url-to-laravel/test. This is mainly used to avoid duplicate content and improve SEO performance.
To do so, you have to register the middleware in the app/Http/Kernel.php
file like this:
//app/Http/Kernel.php
/**
* The application's route middleware.
*
* @var array
*/
protected $routeMiddleware = [
/**** OTHER MIDDLEWARE ****/
'https' => \ForceHttps\Middleware\RedirectToHttps::class,
// REDIRECTION MIDDLEWARE
];
// /routes/web.php
Route::middleware('https')
->group(function() {
/** ADD ALL SECURE ROUTES INSIDE THIS GROUP **/
Route::get('/', function()
{
//
});
Route::get('test',function()
{
//
});
});
/** OTHER PAGES THAT SHOULD NOT BE SECURE **/
In order to edit the default configuration for this package you may execute:
php artisan vendor:publish --provider="ForceHttps\ServiceProvider"
After that, config/force-https.php
will be created. Inside this file you will find all the fields that can be
edited in this package.
Since you will typically need to overwrite the assets every time the package is updated, you may use the --force flag:
php artisan vendor:publish --provider="ForceHttps\ServiceProvider" --force
View changelog here -> changelog