Laravel 5.1强制非WWW和HTTPS不工作

时间:2015-10-11 18:50:15

标签: php .htaccess laravel laravel-5.1

我正试图在我的laravel网站上强制使用https和非www。这是我的.htaccess文件:

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]

以下是当前的重定向

工作重定向

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

直接指向正确的网址正常

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

不工作重定向

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)

当我不在主页上时,我无法弄清楚为什么它会重定向到index.php文件。

1 个答案:

答案 0 :(得分:9)

在寻找解决方案2小时后,结果非常简单。

我所要做的就是将.htaccess文件的顺序更改为

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]