nginx accept HTTP & HTTPS requests on two different ports

I have one nginx server setup(two config files) with two gunicorn web servers setup and running. One gunicorn is production and the other is staging.

I want nginx to serve http requests to xyz.com as well as https requests to xyz.com to the production gunicorn server @ 127.0.0.1:8000.

I have accomplished this with:

server {
   listen 80;
   server_name xyz.com;
   return 301 https://$http_host$request_uri;
}

server {
   listen 443 ssl;
   server xyz.com;
   ..... <<< ssl stuff
  location /{
      .... proxy_stuff
      proxy_pass http://127.0.0.1:8000;
  }
}

I also want http traffic to xyz.com:8080 and https traffic to xyz.com:8080 to hit the staging server @ 127.0.0.1:8081. I have been been able to get https traffic to xyz.com:8080 working as follows:

server {
   listen 8080 ssl;
   server_name xyz.com;
   ...... << ssl stuff
   location / {
      ...... << proxy stuff
      proxy_pass http://127.0.0.1:8081;
   }
}

But I can't seem to find a way to redirect http traffic at xyz.com:8080 to https traffic at xyz.com:8080. I have tried the same redirection that I did with port 80 but have not been successful.

Could use some direction.


Solution 1:

Based on what you've said you want to listen for http and https on port 8080, which I don't believe is possible. Set up different server blocks for different ports, with the location block inside you can have the same proxy_pass to pass to wherever you like.

This is probably about the closest you can get to what you've said, which is listening on 8080 http, 8081 https, and forwarding from http to https. The rewrite might not be exactly right, but you get the idea.

server {
  listen 8080; # HTTP
  server_name example.com;
  rewrite ^ https://example.com:8081$request_uri? redirect;
  # rewrite ^ https://example.com:8081 redirect; # Alternate rewrite
}

server {
  listen 8081 ssl;
  server_name example.com;
  // ...... << ssl stuff
  location / {
    // ...... << proxy stuff to forward to http
    proxy_pass http://127.0.0.1:8080;
    // If you are not proxying to a service on the same server you can use the line below
    // proxy_pass http://example.com:8080; 
  }
}