在網路通信中,若只使用 HTTP,請求內容可能被攔截或重放。HTTPS 透過 SSL 加密與身份驗證,能提升傳輸安全性。本文說明如何使用自簽憑證,在 Nginx 伺服器與 iOS 用戶端之間建立 HTTPS 通信。
HTTP 請求若被擷取,攻擊者可進行重放攻擊。雖然可加入時間戳或隨機參數,但網路延遲仍可能造成誤差。相較之下,HTTPS 能提供更完整的加密與驗證機制。
在伺服器命令列中,可依序建立私鑰、移除密碼、建立 CSR、建立憑證,並合併為 PEM 檔。
openssl genrsa -des3 -out server.key 2048
openssl rsa -in server.key -out server.key
openssl req -new -key server.key -out server.csr
openssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt
openssl x509 -in server.pem -outform der -out server.cer
其中,server.cer 可放入 iOS App,用於用戶端驗證。若需要將憑證與私鑰合併為 PEM,可將 server.crt 與 server.key 合併輸出至 server.pem。
可使用 nginx -t 測試設定檔並確認路徑。接著在 http 區塊中加入 server 設定:
server {
listen 443;
server_name localhost;
index index.html index.htm index.php;
root 網站根目錄;
ssl on;
ssl_certificate 伺服器憑證 server.crt 的絕對路徑;
ssl_certificate_key 伺服器私鑰 server.key 的絕對路徑;
location ~ .*\.(php|php5)?$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
expires 30d;
}
location ~ .*\.(js|css)?$ {
expires 1h;
}
include nginx 的 conf 目錄路徑 rewrite/default.conf;
access_log nginx 服務器日誌路徑 default.log;
}
修改完成後,可重新載入設定:
nginx -t
nginx -s reload
若使用 CA 簽發的憑證,可直接使用 HTTPS 請求。若使用自簽憑證,則需讓 App 信任該憑證。以 AFNetworking 為例:
AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
policy.allowInvalidCertificates = YES;
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = policy;
完成設定後,即可使用 manager 發送 HTTPS 請求。正式環境仍建議使用受信任 CA 簽發的憑證,自簽憑證較適合測試或內部系統。
