今天給大家帶來的是一篇關於通過nginx搭建HTTPS訪問轉跳后端HTTP的教程,部署方式如下:
安裝基礎組件
yum -y isntall firewalld
yum -y install gcc gcc-c++
yum -y install pcre-devel
yum -y install zlib-devel
yum -y install openssl openssl-devel
1
2
3
4
5
下載源碼與編譯
下載與代碼(假設當前在 ~/ 目錄下)
wget https://nginx.org/download/nginx-1.12.2.tar.gz
wget https://www.openssl.org/source/openssl-1.0.2n.tar.gz
1
2
解壓
cd /opt
tar zxf nginx-1.12.2.tar.gz
tar zxf openssl-1.0.2n.tar.gz
1
2
3
編譯前配置,讓nginx支持ssl_module與openssl
cd nginx-1.12.2
./configure --with-http_ssl_module --with-openssl=/opt/openssl-1.0.2n
1
2
編譯
make
make install
1
2
安裝完成后的nginx路徑是: /usr/local/nginx
配置環境
到騰訊雲申請證書(自創建證書參看網上其他資料)
把nginx目錄下的2個文件復制到 /usr/local/nginx/conf 目錄下
配置nginx
vim /usr/local/nginx/conf/nginx.conf
1
在nginx.conf中增加HTTP/HTTPS配置
upstream tomcat {
server 127.0.0.1:9081 fail_timeout=0; #后端服務地址
}
server {
listen 443;
ssl on;
server_name host.httpsDomain.com; #申請證書的域名
ssl_certificate 1_host.httpsDomain.com_bundle.crt; #證書壓縮包中nginx文件夾下crt文件,相對路徑是在 [/usr/local/nginx/conf]
ssl_certificate_key 2_host.httpsDomain.com.key; #證書壓縮包中nginx文件夾下crt文件,相對路徑是在 [/usr/local/nginx/conf]
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2 SSLv2 SSLv3; #指定SSL服務器端支持的協議版本
ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; #指定加密算法
ssl_prefer_server_ciphers on; #在使用SSLv3和TLS協議時指定服務器的加密算法要優先於客戶端的加密算法
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto https;
proxy_redirect off;
proxy_connect_timeout 240;
proxy_send_timeout 240;
proxy_read_timeout 240;
# note, there is not SSL here! plain HTTP is used
proxy_pass http://tomcat;
}
}
server {
listen 80;
server_name host.httpsDomain.com; #http訪問入口
location / {
rewrite ^ https://$http_host$request_uri? permanent; #強制跳轉到HTTPS上
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
保存退出
:wq
1
啟動nginx
#啟動
/usr/local/nginx/sbin/nginx
#重啟
/usr/local/nginx/sbin/nginx -s reload
#關閉
/usr/local/nginx/sbin/nginx -s stop
1
2
3
4
5
6
7
8
9
配置防火牆
把firewalld注冊成服務並啟動
systemctl enable firewalld
systemctl start firewalld
1
2
允許TCP協議下的 80,443 端口 暴露到互聯網
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --zone=public --add-port=443/tcp --permanent
firewall-cmd --reload
1
2
3
運行測試
檢查防火牆端口
firewall-cmd --list-ports
#看看輸出有沒有80/tcp與443/tcp
1
2
PS:如果用的是用阿里雲/騰訊雲,則還需要到XX雲控制台檢查安全策略組是否開放了TCP下的80與443
檢查nginx服務
ss -ntlp | grep nginx
#確認一下 80/tcp 跟 443/tcp 是否被nginx所使用
1
2
瀏覽器測試
如果大家有什么問題或建議,歡迎留言 ^_^
