我在 Namecheap 上有一个域,通过
ALIAS
指向我的 Heroku 实例。
ALIAS @ example.com
我在 Heroku 实例上启用了自动 SSL 证书。
访问
http://example.com
和 https://example.com
有效。
但是,我想通过强制执行 HTTPS 来禁止 HTTP 导航。
根据 Heroku 的说法,这必须在应用程序级别处理。
如何使用 SvelteKit 做到这一点?
您必须创建一个服务器钩子,用于拦截请求、分析其 URL 并重定向到其 HTTPS 等效项。
在
src/hooks.server.ts
// Based on this environment variable, we will redirect or not. Useful to develop without SSL.
import { HTTPS_ENABLED } from '$env/static/private';
import type { Handle } from '@sveltejs/kit';
export const handle: Handle = async ({ event, resolve }) => {
// If enabled, we start processing the request's URL.
if (HTTPS_ENABLED === 'true') {
// As recommended by Heroku, we check the header 'X-Forwarded-Proto' they add on the fly,
// to verify the scheme of the original request.
const forwardedProto = event.request.headers.get('X-Forwarded-Proto');
// If either the original scheme or the one forwarded by Heroku is 'http', we redirect.
if (event.url.protocol === 'http:' || forwardedProto === 'http') {
// We parse the URL to replace whatever scheme set by 'https'.
const protoIndex = event.url.href.indexOf(':');
return new Response(null, {
status: 301,
headers: { location: 'https' + event.url.href.substring(protoIndex) }
});
}
}
return await resolve(event);
};