如何為HTTPS配置Nginx

如何使用“讓我們加密”在Web服務器上設置HTTPS

我最近使用官方的Node.js發行版在DigitalOcean上設置了VPS,它安裝了帶有Node和Nginx作為反向代理的Ubuntu Linux,這意味著它是用戶和Node.js應用之間的中間人。

默認情況下,Droplet配置為使用HTTP,但是我們希望使用HTTPS(HTTP的安全版本)為我們的應用程序提供服務。

因此,我們需要做一些涉及使用Certbot通過獲取SSL證書讓我們加密,並配置Nginx以使用它。

這些是我們將要執行的步驟:

安裝Certbot和Certbot Nginx軟件包

這些說明假設您使用的是Ubuntu,Debian或其他使用apt-get管理軟件包:

sudo apt-get install certbot python3-certbot-nginx

設置Nginx

編輯/etc/nginx/sites-available/default設置正確的服務器名稱(對於SSL而言必不可少)

sudo nano /etc/nginx/sites-available/default

找到線server_name並輸入您的域名:

server_name my.domain.com;

Now run

sudo systemctl reload nginx

to reload Nginx with the updated configuration.

The firewall should already be configured to accept HTTPS, find it out typing sudo ufw status. You should see Nginx Full in the list. If you only see Nginx HTTP, look up how to change that.

Generate the SSL certificate using Certbot

Now we can invoke Certbot to generate the certificate. You must run this as root:

sudo certbot --nginx -d my.domain.com

(of course, change my.domain.com to your domain name)

Enter your real email, as that will be used to communicate you any problem.

I also suggest to choose the option to redirect HTTP to HTTPS automatically.

That’s it!

SSL certificates are valid for 90 days, and Certbot is already set up for automated renewal. To simulate and test-drive the renewal process, run:

sudo certbot renew --dry-run

This should give you a successful message.

That’s it, now your Node apps should successfully run on HTTPS with no additional changes on your part.


More network tutorials: