利用nginx实现https转http

背景

开发同事利用java配置了一个http服务,并配置 80、443 端口对全网开放。但是,测试发现 http://域名 可以打开,而 https://域名 则打不开

解决方案

  • 登录服务器执行 netstat -lnpt | grep 80 确认80端口已监听,所以http://域名 可以打开
  • 登录服务器执行 netstat -lnpt | grep 443 发现443端口并未被监听,所以需要用nginx做一下https到http的转发。
[root@localhost]# netstat -lnpt | grep 443

[root@localhost]# netstat -lnpt | grep 80
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      23952/java

配置过程

  • 第1步,方便起见,这里用yum来安装 nginx
yum install -y nginx
  • 第2步,执行 vi /etc/nginx/nginx.conf 修改 nginx 配置文件,注意 worker_connectionsupstream{}server{}(由于java进程已占用80端口,所以不要再 listen 80;),内容如下:
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 40000;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    upstream tynsrmsp {
        ip_hash;
        server 127.0.0.1:80 weight=2 max_fails=4 fail_timeout=3600;
    }

    server {
        listen      443 ssl;
        server_name tynsrmsp.xxx.com;

        ssl_certificate        /etc/nginx/cert/tynsrmsp.xxx.com.crt;
        ssl_certificate_key    /etc/nginx/cert/tynsrmsp.xxx.com.key;

        location / {
            proxy_pass      http://tynsrmsp;
            proxy_set_header Host               $host:$server_port;
            proxy_set_header Scheme             $scheme;
            proxy_set_header X-Real-IP          $remote_addr;
            proxy_set_header X-Forwarded-Proto  $scheme;
            proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
            proxy_set_header Cookie             $http_cookie;
            client_max_body_size  500m;
            if (-d $request_filename){ rewrite ^/(.*)([^/])$ /$1$2/ permanent; }
        }
    }

}
  • 第3步,拷贝 https 证书文件(.crt 和 .key)到 /etc/nginx/cert 下面
  • 第4步,执行 nginx -t 确认配置无误之后,再启动nginx服务
[root@localhost]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

[root@localhost]# service nginx status
Redirecting to /bin/systemctl status nginx.service
● nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
   Active: inactive (dead)

[root@localhost]# service nginx start
Redirecting to /bin/systemctl start nginx.service
  • 第5步,见证奇迹,浏览器访问 https://域名
Copyright © www.sqlfans.cn 2024 All Right Reserved更新时间: 2022-11-10 14:32:21

results matching ""

    No results matching ""