1. 程式人生 > 實用技巧 >Linux下配置Nginx並使用https協議

Linux下配置Nginx並使用https協議

環境

Centos7.6
nginx-1.17.0

下載

官網:http://nginx.org/download/nginx-1.17.0.tar.gz

環境確認

在安裝nginx前首先要確認系統中是否安裝gccpcre-develzlib-developenssl-devel

  • 檢查是否安裝過軟體包
yum list installed | grep xxx

  • 安裝軟體包
yum -y install gcc pcre-devel zlib-devel openssl openssl-devel


上圖為已安裝


安裝

  • nginx-1.17.0.tar.gz上傳至伺服器並解壓
tar -xzvf nginx-1.17.0.tar.gz

解壓後如下所示:

  • nginx目錄下編譯安裝nginx
./configure --prefix=/usr/local/nginx1.17.0 --conf-path=/usr/local/nginx1.17.0/nginx.conf --with-http_stub_status_module --with-http_ssl_module

--with-http_ssl_module配置nginx支援https協議訪問,不使用https可以不用新增該命令

該命令編譯nginx時將配置檔案nginx.conf生成在nginx目錄下,因編譯後出現錯誤,採用這種方式,詳見後面錯誤記錄,因此,nginx的配置檔案不再是conf

中的nginx.conf

  • 順序執行makemake install編譯
make


make install

  • 測試是否安裝成功
./sbin/nginx -t

  • 啟動nginx
./sbin/nginx

  • 停止nginx
./sbin/nginx -s stop
  • 重啟nginx
./sbin/nginx -s reload
  • 檢視nginx程序
ps -ef | grep nginx

  • 訪問:瀏覽器訪問伺服器IP(nginx預設埠為80),出現如下介面則證明成功

配置HTTPS

  • 伺服器上安裝opensslopenssl-devel
yum install openssl  openssl-devel
  • 建立證書存放目錄
mkdir   /usr/local/nginx/conf/ssl
  • 建立伺服器私鑰
openssl genrsa -des3 -out server.key 2048 #根據提示輸入證書口令

  • 建立簽名請求的證書(CSR
openssl req -new -key server.key -out server.csr  #輸入上面設定的口令,根據提示輸入相應的資訊

  • key進行解密
openssl rsa -in server.key -out server_nopasswd.key

  • 標記證書使用上述私鑰和CSR
openssl x509 -req -days 365 -in server.csr -signkey server_nopasswd.key -out server.crt

  • vim修改nginx配置檔案,載入ssl證書
server {
        listen       443 ssl;
        server_name  localhost;

        ssl_certificate      /usr/local/nginx-1.17.0/conf/ssl/server.crt;
        ssl_certificate_key  /usr/local/nginx-1.17.0/conf/ssl/server.key;

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

        ssl_protocols TLSv1.2;

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

        location / {
            root   html;
            index  index.html index.htm;
        }
    }
  • 輸入證書密碼啟動nginx

  • 瀏覽器訪問測試:https://伺服器IP + 埠443,出現如下介面則成功

錯誤記錄

  • nginx報錯:cp: `conf/koi-win' and `/usr/local/nginx/conf/koi-win' are the same file

該錯誤為編譯安裝nginx時沒有指定conf-path出現的,出現問題的命令:

./configure --prefix=/usr/local/nginx1.17.0 --with-http_stub_status_module --with-http_ssl_module

將命令改為如下指定conf-path後正常:

./configure --prefix=/usr/local/nginx1.17.0 --conf-path=/usr/local/nginx1.17.0/nginx.conf --with-http_stub_status_module --with-http_ssl_module

暫不知具體原因,感謝大佬
centos安裝nginx 報錯:cp: 'conf/koi-win' and '/usr/local/nginx/conf/koi-win' are the same file

.end