How to host a TLS proxy with an existing Apache2 instance with multiple virtual hosts

If you see the need to host a TLS proxy together with your existing Apache powered websites on the standard port (443), there are few options to consider. I went down the nginx path and it was smooth enough to be worth a short blog post.

Apache2 can proxy http/https traffic but not pure tls over tcp, then chatgpt says nginx, haproxy or stunnel is more suitable. I have used nginx a lot previously and decided to try it out, in order to put nginx as frontend, and route a specific sub domain to the TLS proxy, and all the rest to Apache2. Initially I tried out TLS termination with nginx and letting nginx speak http with Apache, but this turned out to be a lot of work since i have quite an intricate Apache setup already. The solution is to use the stream module (install nginx-full on ubuntu) so that nginx is letting Apache handle the TLS termination, and all existing Apache configuration is left intact (except the port shuffling, so that nginx is listening to 443 and Apache on something else):

stream {
  # Map SNI server_name to backend
  map $ssl_preread_server_name $backend {
    yoursubdomain.yourdomain.yourtld tls_upstream_name;
    default apache_https;
  }

  # Apache upstream
  upstream apache_https {
    server 127.0.0.1:8443;
  }

  # TLS service upstream (raw TLS) exposed via Docker in my case
  upstream tls_upstream_name {
    server 127.0.0.1:9443;
  }

  # Catch-all 443 listener
  server {
    listen 443;
    proxy_pass $backend;
    ssl_preread on;
  }
}

This entry was posted in datorer, datorsäkerhet, linux, webbprojekt, webbservern and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *