Nginx:如何将每个 http:port 请求重定向到以下配置中的 HTTPS:port?

Esp*_*sso 3 nginx nginx-reverse-proxy

这是我的 nginx.conf,适用于 https。

如果有人输入HTTP ://dev.local.org:3002 ,如何重定向到HTTPS ://dev.local.org:3002 ?

该 nginx 位于 docker-compose 容器内。

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
}
Run Code Online (Sandbox Code Playgroud)

wol*_*ajr 8

使用497 HTTP错误进行重定向:(来源: https: //meabed.com/http-497-status-code/

在你的conf中你可以添加这样的内容:

 
  listen      1234 ssl;

  server_name your.site.tld;

  ssl         on;

  error_page  497 https://$host:1234$request_uri;
  
}```
Run Code Online (Sandbox Code Playgroud)

  • 哇,真的很有效!谢谢,不知道有这事。唯一的一件事是,这会产生 302 重定向,如果您需要 301 重定向,则应该使用 `error_page 497 =301 https://$host:1234$request_uri;` 代替(已经检查过)。 (4认同)