Nginx配置SSL证书实现https访问及端口映射

http 和 https 介绍

http:应用最广泛的一种网络协议,是一个B/S的request和response的标准,用于从www服务器传输超文本到本地浏览器的传输协议。

https:以安全为目标的http通道,即http下加入ssl层,https的安全基础是ssl,因此加密的详细内容就需要ssl。

两者区别

安全:http是超文本传输协议,信息是明文传输,https则是具有安全性的ssl加密传输协议。

端口:http和https使用的是完全不同的连接方式,用的端口也不一样,前者是80,后者是443。

状态:http的连接很简单,是无状态的;https协议是由ssl和http协议构建的可进行加密传输、身份认证的网络协议,更加安全。

1、依赖

实现https访问,必须要安装http_ssl_module模块,可以通过./nginx -V命令查看

 

 

 如果configure arguments参数里没有--with-http_ssl_module,你就要重新安装nginx了。如何安装nginx可以参考:Linux环境Nginx安装

这里简单说一下:

进入nginx源码目录/usr/local/soft/nginx-1.16.1,执行下面命令:

[root@test1 nginx-1.16.1]# ./configure --prefix=/usr/local/nginx --conf-path=/usr/local/nginx/nginx.conf --with-http_ssl_module
[root@test1 nginx-1.16.1]#make
[root@test1 nginx-1.16.1]#make install

安装不会覆盖原来的nginx.conf文件,请放心。

2、openssl生成证书

在nginx安装目录/usr/local/nginx创建一个ssl文件加

进入ssl目录下执行创建证书命令

openssl req -x509 -nodes -days 36500 -newkey rsa:2048 -keyout /usr/local/nginx/ssl/nginx.key -out /usr/local/nginx/ssl/nginx.crt

如果你的系统没有openssl也需要安装,我在Linux环境Nginx安装讲这篇博客的时候已经安装过了。

会在ssl生产两个证书,nginx.crt就是公钥,nginx.key就是私钥

3、修改Nginx配置

修改前,我们在105上启动一个端口为8080的tomcat,访问地址:http://172.16.43.105:8080/,内容就是tomcat主页。

 

 

修改Nginx.conf文件,配置https访问,大致意思就是我们把通过http://ip:8000端口访问的请求通过rewrite命令重写为https地址,重写URL后,请求会被打到监听端口为443Server配置上。然后找到我们真正的Tomcat服务器ttp://172.16.43.105:8080。

跳转流程:请求-->8000 -->443 -->8080

    server {
        listen       8000;
        server_name  172.16.43.103;
        #rewrite ^(.*)$ https://$host$1 permanent;
        rewrite ^ https://$server_name$request_uri? permanent;
    }


    # HTTPS server
    #
    server {
        listen       443 ssl;
        server_name  172.16.43.103;

        ssl_certificate      /usr/local/nginx/ssl/nginx.crt;
        ssl_certificate_key  /usr/local/nginx/ssl/nginx.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        location / {
            proxy_set_header Host $host;
            proxy_set_header X-Real-Ip $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_pass http://172.16.43.105:8080;
        }
    }

修改完配置后,reload一下。

[root@test1 sbin]# ./nginx -s reload

 

访问http协议:http://172.16.43.103:8000/,观察地址栏变化,nginx已经把http协议转成https协议了。

 

 

结束

posted @ 2021-03-26 14:42  shileishmily  阅读(14421)  评论(1编辑  收藏  举报