问题描述
我试图在子域 Heroku/Laravel 上强制使用 HTTPS。请参阅下面的 .htaccess。
没用。相反,子域“https://sub.domain.com/anything”重定向到“https://sub.sub.domain.com/index.PHP”。看到 URL 中的双“sub”和“index.PHP”了吗?
重写引擎开启# 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]
解决方法
你能不能试试下面的 htaccess 文件。仅根据您显示的样本,更改了规则的顺序(无法测试)。请确保在测试任何 URL 之前清除浏览器缓存。
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]
,
另一种更好的解决方案是直接在 Laravel 中而不是在 NGINX 中强制使用 HTTPS。
这种方式 Laravel 直接生成 HTTPS URL,您不必重定向它。
要在 Laravel 中强制使用 HTTPS,您应该在 App\Providers\AppServiceProvider
中添加以下内容:
/**
* Bootstrap any application services.
*/
public function boot()
{
if (!App::environment([
'local','testing',])) {
URL::forceScheme('https');
}
}