Redirect http to https in laravel 5.2

Viewed 11033

I have a Laravel 5.2 project. Recently, I installed an SSL certificate on my website so when I type https://example.com in the browser it works but when I write example.com, it connects by HTTP.

To fix that, I added these lines to my .htaccess file:

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

After that, when I type example.com, the browser redirects me to https://example.com. That's perfect.

The problem is when I try to access the URL http://example.com/download/get/book/volume2, it doesn't redirect me to HTTPS. It redirects me to the index page. If I add the s of https in the URL it works fine but I need the app to redirect me from HTTP to HTTPS.

The route in routes file:

Route::get('download/get/book/{book}'

That route opens a PDF file that I have in privates/storage folder in the browser's tab.

EDIT:

My .htaccess file:

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# require SSL 
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

2 Answers
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

Add the above two lines just below RewriteEngine On in your .htaccess file. It will automatically redirect any traffic destined for http: to https:

Finally, your .htaccess file will look like the following

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Redirect to https
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
Related