需求:
目前 域名 www.xxx.com
購買了一個阿里雲的通配符ssl證書,綁定的域名爲 *.xxx.com
, 現在需要將 www.xxx.com
、 api.xxx.com
、oss.xxx.com
、suyuan.xxx.com
等域名配置可以通過https訪問
直接上代碼:
upstream suyuanserver {
# 正式環境服務
server localhost:8080;
}
server{
listen 80;
server_name api.xxx.com;
# 溯源管理api接口
location /suyuan/ {
index index.html index.htm;
proxy_pass http://suyuanserver/;
proxy_set_header Host $host;
proxy_hide_header X-Forwarded-Port;
}
}
server{
listen 80;
server_name suyuan.xxx.com;
# 溯源管理系統前端
location / {
root /usr/share/nginx/html/suyuan;
index index.html index.htm;
}
# 溯源管理系統後端
location /api/ {
proxy_pass http://suyuanserver/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
server{
listen 80;
server_name oss.xxx.com;
#微信小程序靜態資源
location /mobile/ {
alias /usr/share/nginx/html/mobile/;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
}
以上配置是本來就有的,服務可以以http進行訪問。
- 下面我們再上面配置的基礎上增加配置,使以上服務同時實現https訪問;另外配置
https://www.xxx.com
用來訪問官網,同時http://www.xxx.com
能夠跳轉到https://www.xxx.com
。
server {
listen 443 ssl;
server_name *.xxx.com;
root html;
index index.html index.htm;
ssl_certificate /etc/nginx/ssl/xxx.com/4961356__xxx.com.pem;
ssl_certificate_key /etc/nginx/ssl/xxx.com/4961356__xxx.com.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; #使用此加密套件。
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #使用該協議進行配置。
ssl_prefer_server_ciphers on;
location / {
resolver 8.8.8.8;
if ($host = 'www.xxx.com' ) {
root /usr/share/nginx/html/official;
break;
}
if ($host = 'oss.xxx.com' ) {
proxy_pass http://oss.xxx.com$request_uri; break;
}
if ($host = 'suyuan.xxx.com' ) {
proxy_pass http://suyuan.xxx.com$request_uri; break;
}
if ($host = 'api.xxx.com' ) {
proxy_pass http://api.xxx.com$request_uri; break;
}
}
}
server {
listen 80;
server_name www.xxx.com;
rewrite ^(.*) https://$server_name$1 permanent; # 直接跳轉到https
}
-
配置也很清晰,就是根據不同的 host 代理到不同的服務上,
-
至於這行配置
resolver 8.8.8.8;
參考這篇博客:https://developer.aliyun.com/article/486252 -
按照我的理解,就是再if大括號裏面的這行配置
proxy_pass http://api.xxx.com$request_uri; break;
變量無法正常解析,需要增加 resolver 的配置
參考 : https://developer.aliyun.com/article/486252