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協議了。

 

 

結束


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM