2025/09/09
CloudFront restrict Origin

Create CloudFront Function to associate distribution

画像などを本サイトからしかアクセスできないことに制限するために、CloudFrontのFunctionを使って制限する。

function handler(event) {
    var request = event.request;
    var headers = request.headers;
    var referer = headers.referer ? headers.referer.value : '';
    var origin = headers.origin ? headers.origin.value : '';

    // 1. Define your allowed domains. Include your main site and any subdomains.
    var allowed_domains = [
        'https://60-think.com',      // Main production site
        'https://60-legacy.com'     // Naked domain
    ];

    // 2. Function to check if a header value matches any allowed domain
    function isAllowed(headerValue) {
        if (!headerValue) return false;
        for (var i = 0; i < allowed_domains.length; i++) {
            if (headerValue === allowed_domains[i] || headerValue.startsWith(allowed_domains[i] + '/')) {
                return true;
            }
        }
        return false;
    }

    // 3. Allow the request if it comes from an allowed domain
    if (isAllowed(origin) || isAllowed(referer)) {
        return request;
    }

    // 4. Optional: Allow requests from yourself (CloudFront -> S3) for health checks
    // Check the User-Agent string for Amazon CloudFront health checks
    var userAgent = headers['user-agent'] ? headers['user-agent'].value : '';
    if (userAgent.includes('Amazon-CloudFront-Health-Check')) {
        return request;
    }

    // 5. Deny all other requests
    return {
        statusCode: 403,
        statusDescription: 'Forbidden',
        body: 'Access denied. Hotlinking not permitted.'
    };
}

テスト