Why am I getting 502 bad gateways when sending a redirect due to amazon load balancing?

I am trying to redirect any HTTP requests to my server to HTTPS.

ELB listens on port 80 and redirects the entire request to port 8088 in my application. The application then sends a 301 redirect redirect to the same URL, but with ports disabled and "https: //" added. This forces clients to re-request the URL over HTTPS.

When I test it locally, it works fine, but when I deploy it in EC2 under load balancing, I get 502 Bad Gateway. The server receives the request and seems to send the redirect correctly (as I said, it works when I click the server directly, and not through the load balancer).

+4
source share
1 answer

It turned out that ELB is very picky about what he considers to be a β€œvalid” answer, and will return 502 Bad Gateway if he is dissatisfied. I fixed this by making sure the response from my server had the following headers:

eg. if i listened to http://example.com

I send the answer:

HTTP/1.1 301 Moved Permanently Content-Type: */*; charset="UTF-8" Location: https://example.com/ Content-Length: 0 

This makes ELB happy and everything works.

For interest, here is the code (Java using Simpleframework ):

 private static void startHttpsRedirector() throws IOException { org.simpleframework.http.core.Container container = new org.simpleframework.http.core.Container() { @Override public void handle(Request request, Response response) { Path path = request.getPath(); Query query = request.getQuery(); String rawHost = request.getValue("host"); System.out.println("Raw host: " + rawHost); System.out.println("Raw path: " + path); System.out.println("Raw query: " + query); String host = rawHost.replaceFirst("\\:.*", ""); response.setStatus(Status.MOVED_PERMANENTLY); String redirectTo = "https://" + host + path + (query.values().size() > 0 ? "?" + query : ""); System.out.println("redirectTo = " + redirectTo); response.setContentType("*/*; charset=\"UTF-8\""); response.setValue("Location", redirectTo); response.setContentLength(0); try { response.commit(); response.close(); } catch (IOException e) { e.printStackTrace(); } } }; Server server = new ContainerServer(container); Connection connection = new SocketConnection(server); SocketAddress address = new InetSocketAddress(8088); connection.connect(address); } 

The same code in javascript can be found here: https://gist.github.com/dhobbs/6164710

+3
source

Source: https://habr.com/ru/post/1494673/


All Articles