Nginx中配置http和https做反向代理

时间:2024-03-12 16:07:38

参考:http://www.zslin.com/web/article/detail/73

1.安装

sudo apt-get install nginx

2.配置:

http_demo.conf

#将80端口转发到3000端口
upstream httpdemo{ server user.demo.cn:
3000; } server { listen 80; server_name user.demo.cn; access_log logs/user.log; error_log logs/user.error; location / { proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://httpdemo; } }

 

代理https需要配置对应域名的ssl证书

https_demo.conf

server {
    listen       80;
    listen       443;
    server_name  c.zslin.com;

    ssl                  on;
    ssl_certificate      /etc/nginx/cert/1_c.zslin.com_bundle.crt;
    ssl_certificate_key  /etc/nginx/cert/2_c.zslin.com.key;

    ssl_session_timeout  5m;

    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;

    server_name  zslin.com www.zslin.com *.zslin.com;
    root         /usr/share/nginx/html;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
        proxy_pass  http://website:port;
        proxy_set_header Host      $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_redirect http:// $scheme://; #做https跳转
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    error_page 404 /404.html;
        location = /40x.html {
    }

    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }

}

listen 443:表示监听443端口,即以https提交的请求,上面的listen 80表示同时也监听以http提交的请求;

ssl on:表示开启SSL协议;

ssl_certificate:指定SSL证书的crt文件路径(如果是阿里云的证书则是pem文件);

ssl_certificate_key:指定SSL证书的key文件路径;

其他ssl开头的可以照搬;

proxy_pass:指定代理的地址,可以是外网地址,也可以是内网地址;

proxy_redirect http:// $scheme://:表示在程序中有redirect跳转时,将采用原有传输协议方式跳转,即如果是以https请求,在跳转后依然是https。

配置完成重启Nginx即可以https访问。

3.重启

验证  sudo /usr/sbin/nginx -t

启动 sudo /usr/sbin/nginx -s load