Nginx multiple server setting

以往我在用自己架的的網域服務都是偷懶透過port forwarding來分別存取,像網頁default 的 :80 或 :443就會連到這、:3000連到git server這樣,可是這樣好像就失去大半買domain的好處,所以趁著最近比較有空好好把 nginx 設定了一下,在預設接受所有存取請求的server上設定nginx 就可以連線到其他區網內提供其他服務的server上

whatisnginx> 圖片來源: https://scaleyourcode.com/blog/article/2

  1. 在預設放site設定檔的目錄下/etc/nginx/sites-available為要添加的server建一個新檔,以下是我的例子。跟之前舊的寫在一起也是可以,只是像這樣分開來我覺得比較好看。

sever1.conf

server {                      
    #加個http2 就可以用http2,真是太猛了
    listen 443 ssl http2 default_server;                                      
    listen [::]:443 ssl http2 default_server;                                     
                                                                            
    server_name server1.example.com; #要解析的子域名                     
    ssl_certificate /your_certificate;                
    ssl_certificate_key /your_key;            
                                                                            
    location / {                                                            
                proxy_pass http://10.0.1.234:80; #要轉送的另一台區網內server的IP和port
                #以下可以設定轉送回給請求端的header 
                proxy_set_header X-Real-IP  $remote_addr;                   
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto https;                   
                proxy_set_header X-Forwarded-Port 443;                      
                proxy_set_header Host $host;                                
    }      
    #location block的子路徑玩法
    location /content {
                alias /var/www/example.com/html/example/content;
    }
    location /api {
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_pass http://10.0.1.234:3836;
    }
}      

sever2.conf

server {
    listen 443 ssl http2;

    server_name server2.example.com; #要解析的子域名
    ssl_certificate /your_certificate;                
    ssl_certificate_key /your_key;

    location / {
                proxy_pass http://10.0.2.123:3000; #要轉送的另一台區網內server的IP和port
                proxy_set_header X-Real-IP  $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto https;
                proxy_set_header X-Forwarded-Port 443;
                proxy_set_header Host server2.example.com;
    }
}
  1. 老樣子設定完一樣要記得把設定再從enabled弄個link到available,例:
    ln -s /etc/nginx/sites-available/sever1.conf /etc/nginx/sites-enabled/sever1.conf

  2. 最後重啟nginx讓設定生效
    service nginx restart

Related Article