透過Nginx反向代理及Certbot SSL設定

Nginx reverse proxy and Certbot SSL setting

Baddy Chiang
5 min readSep 13, 2019

Nginx配置(不含SSL設定)

安裝nginx

sudo apt-get install nginx

修改config檔 /etc/nginx/sites-available/llfbeauty.com.conf

server {
listen 80;

server_name llfbeauty.com;

location / {
proxy_pass http://localhost:3000; #反向代理的Nodejs Sever port
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}

建立一個symbolic link到sites-enabled路徑

sudo ln -s /etc/nginx/sites-available/llfbeauty.com.conf /etc/nginx/sites-enabled/

sites-available: 用來存放server可用的配置,一般在這個路徑下修改

sites-enabled: 用來激活並且使用server的配置,一般透過symbolic link方式

重啟nginx服務

sudo service nginx restart

截至目前為止,已完成80 port向3000 port做反向代理的功能。

已可以造訪http://llfbeauty.com

Certbot SSL設定

安裝Certbot

sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository ppa:certbot/certbot
sudo apt update
sudo apt install python-certbot-nginx

免費產生SSL certificate

sudo certbot --nginx

透過--nginx 參數,能自動偵測nginx conf檔中的server_name ,替它們生成certificate files。

過程中的參數幾乎都能Enter略過,除了https redirect的需求除外,如有需要可以選擇2

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
-------------------------------------------------------------------------------
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
-------------------------------------------------------------------------------
Select the appropriate number [1-2] then [enter] (press 'c' to cancel):

重啟nginx服務

sudo service nginx restart

完成443 port向3000 port做反向代理的功能,以及80 port重新導向443 port。

已可以造訪https://llfbeauty.com

Certbot Certificate 自動更新

Certificate的過期更新,並不需要額外設定,因為Certbot會啟一個Cronjob去確保這個問題。

可以透過renew指令,確保更新的正常性。 renew 會進行更新、--dry-run 表示不會儲存新的certificate

sudo certbot renew --dry-run

可以透過certificates指令,確認目前認證狀態。

sudo certbot certificates

Reference:

[1]https://www.codementor.io/marcoscasagrande/installing-express-nginx-app-on-ubuntu-18-04-with-ssl-using-certbot-pdt44g5gs

[2]https://gist.github.com/cecilemuller/a26737699a7e70a7093d4dc115915de8

[3]https://blog.hellojcc.tw/2018/05/02/setup-https-with-letsencrypt-on-nginx/

--

--