# Nginx的二三事 ## 單一網域,使用location配置多專案服務 && upstream應用(e.g. 轉導監聽不同port的websocket服務) ###### tags: `Nginx` --- 因為工作關係, 遇到需求條件的不同,因此有去查詢說如何在nginx上進行配置服務, 也是方便為未來工作上遇到同樣需求時能比較方便XD。 --- **一、單一網域,使用location配置多專案服務** 廢話不多說,先直接上CODE! ``` // e.g. 在某後台專案底下,也需要有會員管理服務 location ^~ /crm-service { alias /var/www/crm/public; if (!-e $request_filename) { rewrite ^ /crm-service/index.php last; } location ~ \.php$ { if (!-f $request_filename) { return 404; } include fastcgi_params; // 注意這裡使用 $request_filename 配上上述的rewrite,依照專案情況調整!! fastcgi_param SCRIPT_FILENAME $request_filename; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php-fpm.sock; # fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; } } ``` 上述為配對到「crm-service」時,即會使用alias的方式去指派專案路徑給另外一個會員專案(php專案)! | 優點 | 缺點 | | -------- | -------- | | 可以在同一網域底下,支援多個服務 | 主專案的PATH要避開已經被使用的子專案PATH | * **同場加映** 如果有前後端分離,而且是前端SPA專案方式: ``` // 假設有一個happy專案(SPA網站) location ^~ /web/happy { alias /var/www/happy/public; index index.html; try_files $uri $uri/ /www/happy/public/index.html; } ``` 像是VUE Router官方也有文件簡介: [點我查看](https://router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90) --- **二、upstream應用(e.g. 轉導監聽不同port的websocket服務)** [官方原始介紹](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#upstream) 這邊是以php的Laravel專案需要一個**架設websocket為例子**(e.g. laravel-echo-server), 因為websocket需要監聽某一個port(e.g. 8888), 而當如果是同一個Server時,並且該Server不方便異動開通port, 可以使用https(443)轉導到8888, 讓其可以正常運作! 需要在該專案的nginx設定以下的code: ``` // upstream 後續的名稱可以自行定義 (範例為websocket) upstream websocket { // 這裡依據server設置 可自行改變 server 127.0.0.1:8888; } server { listen 443 http2 ssl; listen [::]:443 http2 ssl; server_name example.com.tw; ...... ... // 使用結尾帶有.io的特性 轉導到 websocket server location ~* \.io { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; // 在此設定 URL (在此對應上述upstream) proxy_pass https://localhost:8888; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } ... ...... } ``` * **其他,upstream更多應用** 由官方的upstream的介紹,可以了解到還有許多其他特性, 其中一個就是可以進行負載平衡的設定, 並且設定權重, 以下為官方的設定檔: ``` // server 可以使用 IP、Domain 或 Socket... upstream backend { server backend1.example.com weight=5; server 127.0.0.1:8080 max_fails=3 fail_timeout=30s; server unix:/tmp/backend3; server backup1.example.com backup; } ``` --- > 參考文獻 > http://nginx.org/en/docs/http/ngx_http_upstream_module.html#upstream > https://www.claytontan.net/2020/01/09/nginx-%E8%B2%A0%E8%BC%89%E5%B9%B3%E8%A1%A1-load-balancing/