Laravel 5.1强制非WWW和HTTPS无法正常工作

4
我正在尝试在我的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)

直接访问正确的URL没有问题

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个回答

9

搜索两个小时后,解决方案竟然非常简单。

我所需要做的就是更改我的.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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接