Espresso
Espresso

Reputation: 5739

Nginx: How to redirect each http:port requests to HTTPS:port in the below config?

Here is my nginx.conf, works fine for https.

If someone types HTTP://dev.local.org:3002, how do I redirect to HTTPS://dev.local.org:3002 ?

This nginx is inside a docker-compose container.

worker_processes 1;
events {
    worker_connections 1024;
}

#set $my_server_name _ #TODO global variable does not work?

http {
    #DOCKER DNS - using this to resolve docker-compose hosts like 'appsearch', 'kibana' etc
    resolver 127.0.0.11 ipv6=off;

    #include mime.types;
    default_type application/octet-stream;
    #TO read external configuration
    include sites-enabled/*.conf;


    server {  #DEFAULT SERVER
        listen  443 ssl; # Security change
        server_name _;

        include common.conf;
        include /etc/nginx/ssl.conf;

        location / {
            root    html;
            index   index.html  index.htm;
            include common_location.conf;
        }

        error_page  500 502 503 504 /50x.html;
        location = /50x.html {
            root html;
        }

#        location /appsearch { #TODO this /appsearch did not forward. find how to do it.
#              rewrite ^/appsearch(.*) /$1 break;
#              resolver 127.0.0.11 valid=30s ;
#              set $backend http://appsearch:3002;
#              proxy_pass $backend; # Use variable To avoid upstream host not found error.
#        }

    }#server80

    server {
      listen        9200 ssl;
      server_name   _;

      include common.conf;
      include /etc/nginx/ssl.conf;

      location / {
        set $backend http://elasticsearch:9200;
        proxy_pass $backend; # Use variable To avoid upstream host not found error.
        include common_location.conf;
      }
    }#server

    server {
      listen        3002 ssl;
      #server_name   dev.local.org; #TODO yuck, bad to add server name!
      server_name   _;
      include   common.conf;
      include /etc/nginx/ssl.conf;

      location / {
        set $backend http://appsearch:3002;
        proxy_pass $backend; # Use variable To avoid upstream host not found error.
        include common_location.conf;
      }
    }#server

    server {
      listen        5601;
      server_name   _;
      include   common.conf;
      include   /etc/nginx/ssl.conf;

      location / {
        set $backend http://kibana:5601;
        proxy_pass $backend; # Use variable To avoid upstream host not found error.
        include common_location.conf;
      }
    }#server
}

Upvotes: 3

Views: 1601

Answers (1)

woliveirajr
woliveirajr

Reputation: 9483

Use the 497 HTTP error to redirect: (source: https://meabed.com/http-497-status-code/)

In your conf you would add something like this:

 
  listen      1234 ssl;

  server_name your.site.tld;

  ssl         on;

  error_page  497 https://$host:1234$request_uri;
  
}```

Upvotes: 8

Related Questions