I want to redirect the HTTP traffic to HTTPS without using .htaccess file in laravel 5.2? How can i do that, Any solution will be appreciated.
            Asked
            
        
        
            Active
            
        
            Viewed 143 times
        
    1 Answers
1
            
            
        if(empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off"){
    $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $redirect);
    exit();
}
For Laravel 5.2 you can do this:
create new middleware (you can do it by command php artisan make:middleware nameMiddleware, eg. php artisan make:middleware forceSSL
In this middleware (/app/Http/Middleware/nameMiddleware.php) put this:
<?php
namespace App\Http\Middleware;
use Closure;
class nameMiddleware {
    public function handle($request, Closure $next) {
        if (!$request->secure() && env('APP_ENV') === 'prod') {
            return redirect()->secure($request->getRequestUri());
        }
        return $next($request);
    }
}
Register your middleware in /app/http/Kernel.php
$middlewares = [
...
'\app\Http\Middleware\nameMiddleware'
];
Add the middleware to $routeMiddleware array.
After this, you can add the middleware directly into Route::get('/', ['middleware' => 'nameMiddleware'] ...);
 
    
    
        mabezdek
        
- 87
- 1
- 13
- 
                    Thanks brother, your code is running in core php, but i need to run it in laravel where it is not working ? – Mehroz Munir Sep 30 '16 at 05:49
- 
                    You can create a filter: `Route::filter('f.ssl', function() { if( ! Request::secure()) { return Redirect::secure(Request::path()); } });` – mabezdek Sep 30 '16 at 05:51
- 
                    How to create a filter ? can you pleae elaborate – Mehroz Munir Sep 30 '16 at 05:51
- 
                    Brother i am using laravel 5.2 – Mehroz Munir Sep 30 '16 at 05:53
- 
                    and there are no filters in laravel 5.2 as far i know – Mehroz Munir Sep 30 '16 at 05:54
- 
                    your answer is also right, but the proper procedure is described here which i have follow and worked. http://stackoverflow.com/questions/28402726/laravel-5-redirect-to-https – Mehroz Munir Sep 30 '16 at 06:19
