nginx使用ssl模塊配置支持HTTPS訪問【解決ssl錯誤】

默認狀況下ssl模塊並未被安裝,若是要使用該模塊則須要在編譯nginx時指定–with-http_ssl_module參數.html

需求:
作一個網站域名爲 www.localhost.cn 要求經過https://www.localhost.cn進行訪問.nginx

10.10.100.8 www.localhost.cn

實驗步驟:vim

1.首先確保機器上安裝了openssl和openssl-devel服務器

1
2
#yum install openssl
#yum install openssl-devel

2.建立服務器私鑰,命令會讓你輸入一個口令:session

1
2
openssl genrsa -des3 - out  server.key 1024<br>                                                    //生成私鑰
#由於之後要給nginx使用。每次reload nginx配置時候都要你驗證這個PAM密碼的.因爲生成時候必須輸入密碼,你能夠輸入後 再刪掉。

3.建立簽名請求的證書(CSR):測試

1
openssl req - new  -key server.key - out  server.csr                                 //生成證書頒發機構,用於頒發公鑰

4.在加載SSL支持的Nginx並使用上述私鑰時除去必須的口令:網站

1
2
cp server.key server.key.org
openssl rsa - in  server.key.org - out  server.key                                   //除去密碼以便reload詢問時不須要密碼

5.配置nginx
最後標記證書使用上述私鑰和CSR:加密

1
openssl x509 -req -days 365 - in  server.csr -signkey server.key - out  server.crt

6.修改Nginx配置文件,讓其包含新標記的證書和私鑰:spa

1
2
3
4
5
#vim /usr/local/nginx/conf/nginx.conf
http {
 
         include server/*.cn;
}

7.修改Nginx配置文件,讓其包含新標記的證書和私鑰:code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#vim /usr/local/nginx/server/www.localhost.cn
server {
         listen       443;                                                                        //監聽端口爲443
         server_name  www.localhost.cn;
  
         ssl                   on ;                   //開啓ssl
         ssl_certificate      /etc/pki/tls/certs/server.crt;       //證書位置
         ssl_certificate_key  /etc/pki/tls/certs/server.key;       //私鑰位置
         ssl_session_timeout  5m;
         ssl_protocols  SSLv2 SSLv3 TLSv1;             //指定密碼爲openssl支持的格式
         ssl_ciphers  HIGH:!aNULL:!MD5;               //密碼加密方式
         ssl_prefer_server_ciphers    on ;              //依賴SSLv3和TLSv1協議的服務器密碼將優先於客戶端密碼
  
         location / {
             root   html;                         //根目錄的相對位置
             index  index.html index.htm;
         }
     }

8.啓動nginx服務器.

1
#/usr/local/nginx/sbin/nginx -s reload //若是環境容許的話直接殺掉進程在啓動nginx

若是出現「[emerg] 10464#0: unknown directive "ssl" in /usr/local/nginx-0.6.32/conf/nginx.conf:74」則說明沒有將ssl模塊編譯進nginx,在configure的時候加上「--with-http_ssl_module」便可

1
如:[root@localhost nginx-1.4.4]# ./configure --prefix=/usr/local/nginx --user=www -- group =www --with-http_stub_status_module --with-http_ssl_module

9.測試網站是否可以經過https訪問

1
https: //www.localhost.cn

另外還能夠加入以下代碼實現80端口重定向到443

1
2
3
4
5
6
server {
listen 80;
server_name www.localhost.cn;
#rewrite ^(.*) https://$server_name$1 permanent;
rewrite ^(.*)$  https: //$host$1 permanent;
}

過如下配置,能夠設置一個虛擬主機同時支持HTTP和HTTPS

1
2
listen 80;
listen 443  default  ssl;
相關文章
相關標籤/搜索