Home > Blockchain >  Nginx how to redirect http to https?
Nginx how to redirect http to https?

Time:08-10

I'm kind of new in aws services and nginx configuration. I'm using nginx and my EB instance is a single instance with load balancer at classic mode in front of it.

I have this config file in system:

      server {
        listen 80;
        server_name _;
        return 301 https://$host$request_uri;
      }

      server {
        listen 8080;

        if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2})") {
            set $year $1;
            set $month $2;
            set $day $3;
            set $hour $4;
        }
        access_log /var/log/nginx/healthd/application.log.$year-$month-$day-$hour healthd;
        access_log  /var/log/nginx/access.log  main;

        location / {
            proxy_pass  http://nodejs;
            proxy_set_header   Connection "";
            proxy_http_version 1.1;
            proxy_set_header        Host            $host;
            proxy_set_header        X-Real-IP       $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        }

the machine is behind load-balancer of aws elastic beanstack and EC2 that already configer to make a redirect from 80 to 443 according to aws docs https://aws.amazon.com/premiumsupport/knowledge-center/elb-redirect-http-to-https-using-alb/

the problem here is that the redirect from http to https is not working, and i am unable to access my website when i come from http to https.

weird scenario when i visited my website http://something.com and then make refresh its make the redirect to https://something.com as i want to but not immediately. any suggestion how to solve this problem?

*both http and https access work fine but i want that all my clients that access from http redirect them to https.

CodePudding user response:

i did this solution and its work node.js side

    if((!req.secure) && (req.get('X-Forwarded-Proto') !== 'https') && !req.get('Host').includes('localhost')) {
        res.redirect('https://'   req.get('Host')   req.url);
    }
    else next();
});```
  • Related