如果你想让你的应用程序只能通过 HTTPS 连接访问,可以使用 HttpsEnforcerMiddleware
use Cake\Http\Middleware\HttpsEnforcerMiddleware;
// Always raise an exception and never redirect.
$https = new HttpsEnforcerMiddleware([
'redirect' => false,
]);
// Send a 302 status code when redirecting
$https = new HttpsEnforcerMiddleware([
'redirect' => true,
'statusCode' => 302,
]);
// Send additional headers in the redirect response.
$https = new HttpsEnforcerMiddleware([
'headers' => ['X-Https-Upgrade' => 1],
]);
// Disable HTTPs enforcement when ``debug`` is on.
$https = new HttpsEnforcerMiddleware([
'disableOnDebug' => true,
]);
// Only trust HTTP_X_ headers from the listed servers.
$https = new HttpsEnforcerMiddleware([
'trustProxies' => ['192.168.1.1'],
]);
如果接收到的非 HTTP 请求没有使用 GET 方法,将引发 BadRequestException
。
注意: 当你的网站仅通过 HTTP 访问时,浏览器会忽略 Strict-Transport-Security 标头。一旦你的网站通过 HTTPS 访问,并且没有证书错误,浏览器就会知道你的网站支持 HTTPS,并将遵守 Strict-Transport-Security 标头。
当你的应用程序需要 SSL 时,设置 Strict-Transport-Security
标头是一个好主意。这个标头值在浏览器中被缓存,并且通知浏览器它们应该始终使用 HTTPS 连接。你可以使用 hsts
选项配置这个标头。
$https = new HttpsEnforcerMiddleware([
'hsts' => [
// How long the header value should be cached for.
'maxAge' => 60 * 60 * 24 * 365,
// should this policy apply to subdomains?
'includeSubDomains' => true,
// Should the header value be cacheable in google's HSTS preload
// service? While not part of the spec it is widely implemented.
'preload' => true,
],
]);