nginx根據域名轉發服務
背景:申請了一個域名,計劃是用這個域名部署三個不同的服務在同一臺伺服器上,我通過一級、二級域名來區分不同的服務。
如:a.com 對應8080這個服務,b.a.com 對應8081這個服務, c.a.com對應8082這個服務。
首先應該在DNS解析器中配置a.com,b.a.com, c.a.com這三個域名的解析,然後通過nginx轉發。
根據域名配置了三個轉發:
http://www.ha.com 前後端分離,靜態頁面放在web/rest目錄下,後臺請求根據請求路徑轉發到http://localhost:8080
http://images.ha.com 圖片伺服器
https://admin.ha.com 轉發請求到https://localhost:8081
直接上配置:
worker_processes 4; #處理器個數
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
#gzip on;
server {
listen 80;
server_name www.ha.com; #根據域名攔截http服務
access_log logs/portal.access.log; #設定訪問日誌儲存位置和名稱
location / {
root web/rest; #靜態頁面
index index.html;
}
error_page 404 /404.html;
error_page 500 502 503 504 /404.html;
location = /50x.html {
root html;
}
location ^~ /api/ {
proxy_pass http://localhost:8080; #根據請求路徑轉發給後臺服務(將包含/api/的請求轉發)
}
add_header Access-Control-Allow-Origin *; #允許跨域
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
}
server {
listen 80; #根據域名攔截http服務
server_name admin.ha.com;
location / {
root html;
index bad.html; #攔截所有的http請求到html/bad.html,即不允許http訪問,只能通過https訪問
}
}
server {
listen 443 ssl; #根據域名攔截https服務
server_name admin.ha.com;
access_log logs/admin.access.log;
ssl_certificate ../ssl/test.crt;
ssl_certificate_key ../ssl/test.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_pass https://localhost:8081;
}
}
server {
listen 80;
server_name images.ha.com; #根據域名攔截https服務
access_log logs/images.access.log;
location / {
root E:/data/; #圖片存放位置
}
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
}
}