nginx 安裝、配置 http + https 訪問 tomcat 專案以及配置 http 強轉 https
一、在 linux (CentOS)上安裝 nginx
第一步:新增 nginx 儲存庫
xshell> yum install epel-release
第二步:安裝 nginx
xshell> yum install nginx
使用 yum 安裝 nginx 後,nginx 的預設路徑為:/etc/nginx
第三步:啟動 nginx
xshell> systemctl start nginx
如果你正在執行防火牆,請執行以下命令以允許 HTTP 和 HTTPS 通訊:xshell> firewall-cmd --permanent --zone=public --add-service=http xshell> firewall-cmd --permanent --zone=public --add-service=https xshell> firewall-cmd --reload
第四步:訪問 nginx 以驗證安裝是否成功
由於 nginx 預設的埠號為 80 ,直接在瀏覽器上輸入你的 ip 地址 +80 埠號(例如:111.111.111.111:80),能夠訪問到
nginx 的頁面即表示 nginx 已經安裝成功。類似於下圖。
第五步: 設定系統啟動時候啟用 nginx
xshell> systemctl enable nginx
二、使用 nginx 配置域名訪問 tomcat 專案
第一步: 開啟 nginx 的配置檔案 nginx.conf。
具體路徑:/etc/nginx/nginx.conf
第二步:配置檔案需要修改的原始碼(配置講解在第三步)
upstream xx{ server 193.112.53.11:8080; } server { listen 80 default_server; listen [::]:80 default_server; server_name www.yyddd.cn; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { proxy_pass http://xx/cz_manager/; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } }
第三步:配置檔案修改講解
第四步:配置完成後儲存,然後重啟(重新載入) nginx ,不然訪問不到
xshell> nginx -s reload
第五步:驗證
在瀏覽器上,輸入自己配置的域名,如果能訪問到配置的專案,就說明配置成功。如果還有什麼不懂的話可以給
我留言。
三、nginx 配置 https
第一步:申請證書
關於證書的申請,請轉步看我另外一篇部落格的第一部分:
第二步:把證書上傳到伺服器上
下面是我在騰訊雲申請的 ssl 證書,下載證書後,開啟的檔案內容如下,我們使用的是 nginx 配置 https ,所有
開啟 Nginx 檔案,把檔案下的兩個檔案上傳到伺服器上(放在哪裡自己決定,知道路徑就行,後面配置需要用到
證書的路徑)
第三步:開啟配置檔案 nginx.conf
1.在配置檔案中,找到下面這段程式碼,把註釋給去掉,或者直接複製我下面這段程式碼進行修改也行。
server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
server_name www.yydddd.cn;
root /usr/share/nginx/html;
ssl_certificate "/etc/nginx/1_yydddd.cn_bundle.crt";
ssl_certificate_key "/etc/nginx/2_yydddd.cn.key";
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 10m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
proxy_pass http://xx/cz_manager/;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
2.配置解析
3.配置完成後儲存,然後重啟(重新載入) nginx ,不然訪問不到
xshell> nginx -s reload
4.驗證
直接在瀏覽器輸入:https://www.yydddd.cn(請換成自己的域名)
能夠正常訪問到的話,就是配置 https 成功了。
四、nginx 強制使用 https 訪問
所謂強制使用 https 訪問,就是使用者使用 http 訪問的時候,直接轉到 https 訪問。
只需要修改 http 的配置即可:
重啟nginx
xshell> nginx -s reload
使用域名(例如:www.yyddd.cn)直接訪問的時候,直接跳轉到 https 訪問的話,就說明配置成功了。