// Nama domain tempat aplikasi HTML Anda di-host sebenarnya.
// GANTI ini dengan URL aplikasi HTML Anda yang sebenarnya.
const HTML_APP_HOST = 'https://YOUR_HTML_APP_URL.com';
/**
* Event listener untuk permintaan masuk.
* Fungsi ini mencegat semua permintaan HTTP yang masuk ke Worker.
* @param {FetchEvent} event
*/
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
/**
* Menangani permintaan HTTP.
* Berfungsi sebagai reverse proxy untuk meneruskan permintaan ke aplikasi HTML Anda.
* @param {Request} request
* @returns {Response}
*/
async function handleRequest(request) {
const url = new URL(request.url);
// Buat URL baru yang mengarah ke aplikasi HTML Anda
// Pertahankan jalur asli, parameter kueri, dll.
const newUrl = new URL(url.pathname + url.search, HTML_APP_HOST);
// Buat objek permintaan baru.
// Ini penting untuk meneruskan header asli, metode, body, dll.
const newRequest = new Request(newUrl.toString(), {
method: request.method,
headers: request.headers,
body: request.body,
redirect: 'follow' // Ikuti redirect dari server HTML
});
// Lakukan permintaan ke aplikasi HTML Anda
const response = await fetch(newRequest);
// Periksa apakah respons adalah redirect ke URL lama
// dan perbarui itu untuk mengarah kembali ke domain Worker.
const contentType = response.headers.get('content-type');
if (response.status >= 300 && response.status < 400 && response.headers.has('location')) {
const location = response.headers.get('location');
if (location && location.includes(HTML_APP_HOST)) {
const newResponse = new Response(response.body, response);
newResponse.headers.set('Location', location.replace(HTML_APP_HOST, url.origin));
return newResponse;
}
}
// Mengembalikan respons dari aplikasi HTML
return response;
}