diff --git a/.env.default b/.env.default index 05c3bed..d119f02 100644 --- a/.env.default +++ b/.env.default @@ -4,4 +4,4 @@ DEBUG=false # Frontend specific VITE_API_TARGET=https://pies.com -VITE_ALLOWED_HOST=pies.com \ No newline at end of file +VITE_ALLOWED_HOST=pies.com # for sub domens add . before host address \ No newline at end of file diff --git a/kittyurl-frontend/vite.config.ts b/kittyurl-frontend/vite.config.ts index e9f29b9..f5ae0de 100644 --- a/kittyurl-frontend/vite.config.ts +++ b/kittyurl-frontend/vite.config.ts @@ -1,29 +1,67 @@ -import { defineConfig, loadEnv } from 'vite' +import { defineConfig, loadEnv, type Plugin } from 'vite' // Zmieniono na 'type Plugin' import react from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import path from 'path' -export default defineConfig(({ mode }) => { - // Ścieżka do folderu nadrzędnego - const envDirectory = path.resolve(__dirname, '..'); +// Plugin obsługujący logikę przekierowań +const domainRedirectPlugin = (targetUrl: string, useSubdomains: boolean, debug: boolean): Plugin => ({ + name: 'domain-redirect', + configureServer(server) { + server.middlewares.use((req, res, next) => { + const host = req.headers.host; // np. "ssss.localhost:6568" + if (!host) return next(); - // Wczytujemy zmienne do użytku + const hostname = host.split(':')[0]; // usuwamy port, zostaje "ssss.localhost" + const targetHost = new URL(targetUrl).hostname; + + // LOGIKA TESTOWA DLA LOCALHOST: + // Jeśli host to np. ssss.localhost, a nie czysty localhost: + const isSubdomainOfLocalhost = hostname.endsWith('.localhost'); + const isPureLocalhost = hostname === 'localhost' || hostname === '127.0.0.1'; + + if (debug) { + console.log(`[Debug] Host: ${hostname}, SubOfLocal: ${isSubdomainOfLocalhost}, Pure: ${isPureLocalhost}`); + } + + // Przekieruj jeśli: + // 1. To subdomena localhosta (do testów) + // 2. LUB to subdomena ktty.is, a subdomeny są wyłączone + if ((isSubdomainOfLocalhost && hostname !== 'localhost') || (!useSubdomains && hostname !== targetHost && !isPureLocalhost)) { + if (debug) console.log(`[Redirect] Z ${hostname} na ${targetUrl}`); + + res.writeHead(301, { Location: `${targetUrl}${req.url}` }); + return res.end(); + } + + next(); + }); + } +}); + +export default defineConfig(({ mode }) => { + const envDirectory = path.resolve(__dirname, '..'); const env = loadEnv(mode, envDirectory, ''); - return { - - envDir: envDirectory, + // Twoje zmienne z .env + const publicUrl = env.PUBLIC_URL; + const useSubdomains = env.USE_SUBDOMAINS === 'true'; + const isDebug = env.DEBUG === 'true'; + return { + envDir: envDirectory, plugins: [ react(), tailwindcss(), + domainRedirectPlugin(publicUrl, useSubdomains, isDebug) ], server: { port: 6568, + host: true, }, preview: { port: 6568, - allowedHosts: [env.VITE_ALLOWED_HOST], + + allowedHosts: [env.VITE_ALLOWED_HOST , 'localhost'], }, } }) \ No newline at end of file