HTTPS redirects on Heroku Laravel not working correctly

Viewed 510

I tried to force HTTPS on subdomain Heroku/Laravel. See .htaccess below.

It didn't work. Instead the subdomain "https://sub.domain.com/anything" redirect to "https://sub.sub.domain.com/index.php". See the double "sub" and the "index.php" in the URL?

RewriteEngine On
# 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]

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

# If we receive a forwarded http request from a proxy...
RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]

# ...or just a plain old http request directly from the client
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on

# Redirect to https version
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
2 Answers

Could you please try following htaccess file. Based on your shown samples only, have changed the sequence of your Rules(couldn't test it). Please make sure you clear your browser cache before testing any URLs.

RewriteEngine On

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

# If we receive a forwarded http request from a proxy...
RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]

# ...or just a plain old http request directly from the client
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on

# Redirect to https version
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


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

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

An alternative and better solution is to force HTTPS in Laravel directly and not in NGINX.

This way Laravel generates directly HTTPS URLs, and you don't have to redirect it.

To force HTTPS in Laravel you should add the following inside App\Providers\AppServiceProvider:

    /**
     * Bootstrap any application services.
     */
    public function boot()
    {
        if (!App::environment([
            'local',
            'testing',
        ])) {
            URL::forceScheme('https');
        }
    }
Related