amphp / http-server

An advanced async HTTP server library for PHP, perfect for real-time apps and APIs with high concurrency demands.
https://amphp.org/http-server
MIT License
1.29k stars 100 forks source link

HTTPS Redirection #368

Closed azjezz closed 4 months ago

azjezz commented 5 months ago

I'm trying to figure out if it is possible to configure Amphp server to listen twice on the same port, and do HTTP->HTTPS redirection.

e.g:

$server->expose('127.0.0.1:8080', null);
$server->expose('127.0.0.1:8080', $bindContextWithTls);
$server->start();

...

currenctly, with this configuration, https://127.0.0.1:8080 works as expected, but http://127.0.0.1:8080 fails ( TLS negotiation failed: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:0A00009C:SSL routines::http request ).

I have looked around in the code, and am unable to find a way to achieve what i'm looking for, which is to have http://127.0.0.1:8080 redirect to https://127.0.0.1:8080.

bwoebi commented 5 months ago

No, it's not. The primary reason is that you can only either mark the stream encrypted or not. There's no hybrid "try peeking and conditionally feed back to the stream and switch to TLS" possible with PHP streams. As far as I know at least.

If you know how to, without creating an intermediary stream which optionally redirects into a TLS pipe, you're welcome :-)

azjezz commented 4 months ago

Thank you for your response! I experimented with this idea further and found that although it's challenging to implement, it's not entirely impossible.

The most practical solution I discovered involves setting up a plain TCP server to listen on the desired port (e.g., 8000). Then, two separate HTTP servers could listen on different ports—one for HTTP (e.g., 8001) and another for HTTPS (e.g., 8002). The TCP server could determine the type of the incoming connection by inspecting the first few bytes and then forward it to the appropriate server.

I will be closing this issue since implementing this solution is not be justifiable given the complexity involved.