0

Overview:

I would like advice on setting up a reverse proxy so that my Google Cloud Run Python app hosted at example.com proxies content from our Kinsta installation hosted at myblog.kinsta.cloud. For example, example.com/articles/{page} (our main application) should return the same content as myblog.kinsta.com/page

Main Site Setup:

  • My app is hosted on a WSGI Gunicorn server.
  • The web framework that my app uses is Flask.
  • In order to support a reverse proxy, I tried implementing this endpoint:
@app.route('/articles', defaults={'path': ''}, methods=['GET', 'POST'])
@app.route('/articles/<path:path>', methods=['GET', 'POST'])
def articles(path):
    url = f"https://myblog.kinsta.cloud/{path}"  # Construct target URL


    # Forward request headers
    headers = {k: v for k, v in request.headers if k.lower() != 'host'}
    headers['Host'] = 'myblog.kinsta.cloud'  
    headers['X-Forwarded-For'] = request.remote_addr
    headers['X-Real-IP'] = request.remote_addr
    headers['X-Forwarded-Proto'] = request.scheme


    # Make the request
    resp = requests.request(
        method=request.method,
        url=url,
        headers=headers,
        data=request.get_data(),
        cookies=request.cookies,
        allow_redirects=True
    )


    # Filter response headers
    excluded_headers = {'content-encoding', 'content-length', 'transfer-encoding', 'connection'}
    response_headers = {k: v for k, v in resp.headers.items() if k.lower() not in excluded_headers}


    return Response(resp.content, resp.status_code, response_headers)

Subsite Setup:

  • My blog is hosted on Kinsta, which automatically gives an initial domain that looks like myblog.kinsta.cloud.
  • I asked Kinsta Support to set up the reverse proxy on their end (they have a reverse proxy add-on). They said that in the wp-config file, they added the following code:
$_SERVER['HTTP_HOST'] = 'https://example.com';


/*Include, ONLY if the main site is SSL forced*/
define('FORCE_SSL_ADMIN', true);
if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
               $_SERVER['HTTPS']='on';

  • And they also made the following changes in their nginx config.
rewrite ^/articles/(.*)$ /$1 last;

Issue:

Whenever I go to example.com/articles/{page}, the URL changes to example.com/{page} and I see a page not found error.

Question:

Can you please tell me if there's something wrong with how I implemented the reverse proxy in Python?

Thank you!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.