Warm tip: This article is reproduced from serverfault.com, please click

The plain HTTP request was sent to HTTPS port

发布于 2021-01-14 01:10:57

I have the next NGINX proxy configuration

http {
    server_tokens off;
server {
    listen     7443 ssl;
    ssl_certificate     /etc/nginx/ssl/star.crt;
    ssl_certificate_key /etc/nginx/ssl/star.key;
    location /prometheus/ {
      auth_basic           "Prometheus";
      auth_basic_user_file /etc/nginx/.htpasswd;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      # I leave this hardcoded for now
      proxy_pass http://prometheus:9090/prometheus/;
   }

    location / {
      auth_basic           "Prometheus";
      auth_basic_user_file /etc/nginx/.htpasswd;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      # I leave this hardcoded for now
      proxy_pass http://alertmanager:9093;
   }
 }
}
events {}

If I enter in browser URL without specification of HTTPS by using port 7443, I get:

The plain HTTP request was sent to HTTPS port

For example: prometheus.example.com:7443/prometheus/ or prometheus.example.com:7443/#/alerts/

How can I make NGINX redirect to HTTPS automatically if I specify such URLs without HTTPS?

Questioner
user54
Viewed
0
user54 2019-02-06 17:41:35

Actually the solution was pretty straightforward. In server section under "listen" string I was needed to add only:

error_page 497 https://$host:$server_port$request_uri;

497 code is HTTP Request Sent to HTTPS Port. error_page handles this code and redirects to https://$host:$server_port$request_uri;

where:

$host is reserved variable which represents hostname on which NGINX is being run.

$server_port is reserved variable which represents listining port which is declared in server section.

$request_uri is reserverd variable which represents full original request URI (with arguments).