amazon-ec2reverse-proxycaddy

Trying to redirect api calls to backend with Caddy reverse proxy but getting error 405


I have a backend (spring) and frontend (react) deployed in an EC2 instance, backend is running on port 8080. The frontend uses axios with a baseUrl: baseURL: "https://website.com/"

The idea is to redirect requests like "https://website.com/api/something" to the backend instead and I was trying to do it with caddy with this configuration:

www.website.com {
        redir https://website.com{uri} # Ensure the `www` subdomain redirects to the root domain
}


website.com {
        root * /var/www/html # Path to your React app's build folder

        # Serve static files (React app)
        file_server

        # Redirect all routes not matching files to index.html for client-side routing
        try_files {path} /index.html 

        reverse_proxy /api/* localhost:8080 # Proxy requests to backend API
}

When I directly call the backend with <ec2InstanceIp>:8080 in Postman I get a correct answer but when I try through the website I get 405 (Method Not Allowed)

I noticed in testing that the backend only responds positively when using http and does not work with https, while my website is using https.

What could be wrong here?


Solution

  • The issue is that try files is being executed always so all the requests no matter the path used end up returning index.html. To fix it I followed a suggestion from Matt Holt in this forum. By using router and switching the reverse proxy to be the first line, the backend starts being called before.

    # Main site for biospringbok.com
    biospringbok.com {
            root * /var/www/html # Path to your React app's build folder
    
    
            #Route is used to ensure that first reverse proxy is executed and only resort to try files if its not an api call
            route {
                    reverse_proxy /api/* localhost:8080
    
                    # Redirect all routes not matching files to index.html for client-side routing
                    try_files {path} /index.html # This allows React Router to take over for non-file URLs
    
                    # Serve static files (React app)
                    file_server
               }
    }