如何隐藏 webapi url 并显示“漂亮”的 url?

问题描述 投票:0回答:1

我需要为我自己的 URL 缩短服务生成一个漂亮的 URL。
我的网络服务器地址看起来像

https://my-backend-api-server.us-central1.run.app/redirectapp/redirect/wAzclnp3

我不想暴露这一点,而且它也不短。

假设我有一个域

www.mydomain123.com
,我想“美化”我的 URL,以便
www.mydomain123.com/wAzclnp3
将服务于
https://my-backend-api-server.us-central1.run.app/redirectapp/redirect/wAzclnp3
,并且
www.mydomain123.com
www.mydomain123.com/otherapp
将通过我的网络服务器(而不是 api 服务器)提供服务

如何在 django 中执行此操作?

python django dns friendly-url
1个回答
0
投票

我最终按照@grawity_u1686的建议使用了反向代理

我在 CloudFlare.com 中设置了一个工作人员(并在本地使用 wrangler) 代码(比我希望的更复杂)如下。我还必须支持资产,并将我的后端更改为仅返回哈希本身而不是重定向对象。

addEventListener('fetch', event => {
    event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
    const url = new URL(request.url);
    const path = url.pathname;

    console.log(`Incoming request URL: ${url}, Path: ${path}`);

    // Handle /r/{somehash} redirects
    if (path.startsWith('/r/')) {
        const hash = path.substring(3); // Extract "somehash" from "/r/{somehash}"
        
        const backendUrl = `https://backend-1234.us-central1.run.app/app/unhash/${hash}`;
        
        try {
            console.log(`Fetching URL from backend: ${backendUrl}`);

            // Fetch the URL from the backend
            const response = await fetch(backendUrl, {
                method: 'GET',
                headers: request.headers,
            });

            if (!response.ok) {
                throw new Error(`Backend responded with status ${response.status}`);
            }

            console.log(response);

            const data = await response.json();
            const resolvedUrl = data.long_url;

            if (!resolvedUrl) {
                throw new Error('No URL found in backend response');
            }

            console.log(`Resolved URL from backend: ${resolvedUrl}`);

            return Response.redirect(resolvedUrl, 302);
        } catch (error) {
            console.error(`Error resolving /r/${hash}: ${error.message}`);
            return new Response(`Error resolving the redirect: ${error.message}`, {
                status: 502,
                headers: { 'Content-Type': 'text/plain' },
            });
        }
    }

    // Handle static file requests
    if (path.startsWith('/static/') || path.startsWith('/assets/')) {
        const staticUrl = `https://noamzilo.github.io/personal_website${path}`;
        try {
            const staticResponse = await fetch(staticUrl, {
                method: 'GET',
                headers: request.headers,
                redirect: 'follow',
            });

            if (!staticResponse.ok && staticResponse.status !== 404) {
                throw new Error(`Static file fetch failed with status ${staticResponse.status}`);
            }

            return staticResponse;
        } catch (error) {
            console.error(`Error fetching static file: ${error.message}`);
            return new Response(`Error fetching static file: ${error.message}`, {
                status: 502,
                headers: { 'Content-Type': 'text/plain' },
            });
        }
    }

    // Default behavior: Proxy other requests to GitHub Pages
    const githubUrl = `https://noamzilo.github.io/personal_website${path}`;
    try {
        let response = await fetch(githubUrl, {
            method: request.method,
            headers: request.headers,
            body: request.method !== 'GET' && request.method !== 'HEAD' ? request.body : null,
            redirect: 'follow',
        });

        if (response.status === 404) {
            // Serve index.html for client-side routing
            const indexUrl = `https://noamzilo.github.io/personal_website/index.html`;
            response = await fetch(indexUrl, {
                method: 'GET',
                redirect: 'follow',
            });
        }

        // Clone and modify headers
        let newHeaders = new Headers(response.headers);
        newHeaders.set('Access-Control-Allow-Origin', '*');

        return new Response(response.body, {
            status: response.status,
            statusText: response.statusText,
            headers: newHeaders,
        });
    } catch (error) {
        console.error(`Error fetching GitHub Pages: ${error.message}`);
        return new Response(`Error fetching GitHub Pages: ${error.message}`, {
            status: 502,
            headers: { 'Content-Type': 'text/plain' },
        });
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.