Forward all http to https on nginx with existing r

2019-06-02 21:18发布

Preface: I have searched dozens of tutorials for this over the past few days and I can't get any of them to work, which is why I'm asking here. I hope it's something simple that I'm missing. I appreciate any advice I can get!

Ok -- so I'm running a centos 6 vps with nginx installed. I have multiple domains on this vps. On the domain in question, I'm running a node.js app on port 9000. I currently have proxy_pass setup to point www.example.net to www.example.net:9000 -- and that works fine. What I need to do now is take all traffic coming in to http://www.example.net and redirect it to https://www.example.net while preserving the proxy pass for the app on port 9000.

Again, I've tried dozens of different tutorials and stackoverflow answers, but none of them work for me. I've had to revert back to the nginx config that I started with just so I can view my app in a browser. I will post here what I have, and if anyone could point me in the right direction, it would be greatly appreciated!

 server {
    listen      123.45.678.90:80;
    server_name example.net www.example.net;
    error_log  /var/log/httpd/domains/example.net.error.log error;

location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass https://123.45.678.90:9000/;
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";


    }
}

1条回答
Summer. ? 凉城
2楼-- · 2019-06-02 21:49

We do something like this for our setup. Our nginx config for a "redirect all http requests to https" looks something like this:

server {
    listen      123.45.678.90:80;
    server_name example.net www.example.net;
    error_log  /var/log/httpd/domains/example.net.error.log error;

    # Always redirect to HTTPS
    redirect 301 https://www.example.net$request_uri;
}

server {
    listen      123.45.678.90:443 ssl;
    server_name example.net www.example.net;
    error_log  /var/log/httpd/domains/example.net.error.log error;
    ssl_certificate /path/to/server.crt
    ssl_certificate_key /path/to/server.key

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass https://123.45.678.90:9000/;
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

Thus the HTTP server listening on port 80 always issues an HTTP 301 redirect to the HTTPS server listening on port 443.

Hope this helps!

查看更多
登录 后发表回答