How to use nginx to serve two services: one by domain name and the second by ip:port

Viewed 10

I have server with one external IP v4 address, two running services (127.0.0.1:8086 and 127.0.0.1:8089) and nginx. I want to configure nginx to be able to open the first one only using domain name and the second one only by ip+port.

I tried several configuration combinations, but all of them break the rules in some way. Here is the most accurate in my opinion.

user nginx;
worker_processes 1;

error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;


events {
    worker_connections 1024;
}


http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main
        '$remote_addr - $remote_user [$time_local] "$request" '
        '$status $body_bytes_sent "$http_referer" '
        '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;

    sendfile on;

    keepalive_timeout 65;

    # server for the first service
    server {
        listen 443 ssl;
        server_name example.com ;

        ssl_certificate /etc/letsencrypt/live/example.com /fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com /privkey.pem;
        include /etc/letsencrypt/options-ssl-nginx.conf;
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

        location / {
            proxy_pass http://127.0.0.1:8086/;
            proxy_http_version 1.1;

        }

    }
    # redirect http to https for example.com  and refuse the others
    server {

        server_name example.com ;
        listen 80;
        if ($host = example.com ) {
            return 301 https://$host$request_uri;
        }
        return 444;
    }
    # allow to proceed to the second service using ip:port
    server {
        server_name MY_IP_ADDRESS;
        listen 8099;
        location / {
            proxy_pass http://127.0.0.1:8089/;
        }
    }

}

What should i change to match the next conditions:


https://example.com  -> 200 open the first service - working
http://example.com -> 301 redirect to first service - working
http://example.com:8099 -> 444 refuse - not working (opens the second service)
https://example.com:8099 -> 444 refuse - not working (does not open any service, but it proceed to ssl verification step, which it shoudln't do: curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number)

http://MY_IP_ADDRESS -> 444 refuse - working
https://MY_IP_ADDRESS -> 444 refuse - not working (it opens the first service)
http://MY_IP_ADDRESS:8099 -> 200 # open the second service
https://MY_IP_ADDRESS:8099 -> 444 refuse - not working (the same as in https://example.com:8099)
0 Answers
Related