InfamousCoder
InfamousCoder

Reputation: 71

Nginx reverse proxy : Redirect all http requests to https

I have a reverse proxy with Nginx running on port 5000 and I want to redirect all the requests coming to port 5000 as a https request.

Right now I am getting the error : 400 Bad Request The plain HTTP request was sent to HTTPS port

server {
           listen 5000 ssl;
           server_name myserver.com;

           location / {
               proxy_pass                 http://127.0.0.1:8080;
               proxy_set_header           X-Real-IP   $remote_addr;
               proxy_set_header           X-Forwarded-For  \$proxy_add_x_forwarded_for;
               proxy_set_header           X-Forwarded-Proto  $scheme;
               proxy_set_header           X-Forwarded-Server  $host;
               proxy_set_header           X-Forwarded-Host  $host;
               proxy_set_header           Host  $host:5000;


               add_header 'Access-Control-Allow-Methods' 'GET, POST';
               add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';
               add_header 'Access-Control-Allow-Credentials' 'true';

               # here comes the basic auth, after the options part
               auth_basic            'Restricted';
               auth_basic_user_file  path/to/.htpasswd;

           }

           ssl    on;
           ssl_certificate    path/to/crt;
           ssl_certificate_key    path/to/key;
       }

Well I tried with adding

 if ($scheme != "https") {
    rewrite ^ https://$host$request_uri permanent;
 }

 if ($scheme != "https") {
     return 301 https://$host$request_uri permanent;
 }

Nothing seems to solve the issue. What should I do to fix this?

Upvotes: 1

Views: 23950

Answers (3)

InfamousCoder
InfamousCoder

Reputation: 71

Well, using error_page seems to do the trick for me.

  server {
       listen 5000 ssl;
       server_name myserver.com;
       error_page 497 https://$host:5000$request_uri;
       ..
       ..
    }

To know more about the 497 check the "Error Processing" section in http://nginx.org/en/docs/http/ngx_http_ssl_module.html

Upvotes: 0

Mehdi
Mehdi

Reputation: 7403

Assuming http traffic comes via port 80, you may redirect to https by adding an extra server block listening to this port:

server {
    listen 80;
    server_name myserver.com;

    location / {
        return 301 https://myserver.com$request_uri;
    }
}

Upvotes: 6

Rama Schneider
Rama Schneider

Reputation: 64

This may sound simplistic, but have you tried adding "https://" to the front of the domain name you type in? I've found the default is always a plain "http" request.

Upvotes: 0

Related Questions