Search code examples
nginxgraphite

Nginx http redirect to https doesn't work


I am using nginx reverse proxy for my graphite web. My nginx.conf looks somewhat like this

server {
           listen 8081;
           server_name myserver.com;
           return 301 https://$host:5000$request_uri;
       }

 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;


           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;
   }

I start using my site on https://host:5000 and i want any http requests to this site to be redirected as a https request. As of now i see that it gets redirected to http://host/

This happens only during login and logout.

I saw many examples where they used port 80 for listening to http traffic but i cannot use that port as some other application is already using that.

Can someone please help me out in this?


Solution

  • Give a try using $server_name instead of $host, for example:

    server {
       listen 8081;
       server_name myserver.com;
       return 301 https://$server_name:5000$request_uri;
    }
    

    You can indeed put your domain directly on the redirect for example:

    return 301 https://myserver.com:5000$request_uri;
    

    Probably this is not your case but since you are using different ports may be worth to check the error_page 497, this is mainly used when you want to process plain HTTP request which has been sent to HTTPS port:

    server {
      listen      8081 ssl;
      server_name your.site.tld;
      ssl         on;
      ...
      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