Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.1 Force non-WWW and HTTPS Not Working

I am trying to force https and non-www on my laravel site. Here is my .htaccess file:

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]

#if the request is not secure
RewriteCond %{HTTPS} off
#redirect to the secure version
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]

#Redirect to non-WWW
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteRule ^(.*) https://example.com/$1  [QSA,L,R=301]

Here are the current redirects

Working redirects

example.com                  => https://example.com           (GOOD)
www.example.com              => https://example.com           (GOOD)
https://www.example.com      => https://example.com           (GOOD)

Direct to the correct URL works fine

https://example.com          => https://example.com           (GOOD)
https://example.com/asdf     => https://example.com/asdf      (GOOD)

NOT Working redirects

example.com/asdf             => https://example.com/index.php (BAD)
www.example.com/asdf         => https://example.com/index.php (BAD)
https://www.example.com/asdf => https://example.com/index.php (BAD)

I can't figure out why it's redirecting to the index.php file when I'm not on the main page.

like image 283
StackOverflower Avatar asked Jan 07 '23 09:01

StackOverflower


1 Answers

After 2 hours of searching for the solution it turned out to be extremely simple.

All I had to do was change the order of my .htaccess file to

RewriteEngine On

#Redirect to non-WWW
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteRule ^(.*) https://example.com/$1  [QSA,L,R=301]

#if the request is not secure
RewriteCond %{HTTPS} off
#redirect to the secure version
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]

# 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]
like image 74
StackOverflower Avatar answered Jan 16 '23 22:01

StackOverflower