用自己的域名搭建网站(Nginx、免费 HTTPS)
以下是在 Ubuntu 服务器上安装 Web 服务器(Nginx),绑定您的域名,再用免费证书配置 HTTPS(小锁图标)的方法。
1. 安装 Nginx
sudo apt update
sudo apt install -y nginx
如果开启了防火墙(ufw),请开放 Web 端口。(在防火墙中开放端口)
sudo ufw allow 'Nginx Full'
在浏览器中访问 http://server-ip,如果出现“Welcome to nginx!”页面即表示成功。
2. 绑定域名
在购买域名的地方(Gabia、Hosting.kr、Cloudflare 等)的 DNS 管理 菜单中添加记录。
| 类型 | 主机(名称) | 值 |
|---|---|---|
| A | @ | 服务器 IP |
| A | www | 服务器 IP |
DNS 生效通常需要几分钟,长则需要几个小时。在本地电脑上执行以下命令,如果显示服务器 IP,就表示已经绑定。
nslookup example.com
3. 设置您的网站
创建存放网页文件的文件夹,并编写 Nginx 配置文件。(将 example.com 替换为您的域名)
sudo mkdir -p /var/www/example.com
echo '<h1>Hello Nevv!</h1>' | sudo tee /var/www/example.com/index.html
sudo nano /etc/nginx/sites-available/example.com
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html;
}
启用配置并重新加载 Nginx。
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t # 检查配置语法——应显示 "ok"
sudo systemctl reload nginx
如果想接入 Node.js、Python 应用
如果应用在服务器内运行在例如 3000 端口上,请将上面配置中的 root、index 行替换为以下内容。
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
4. 配置 HTTPS(免费证书)
使用可自动签发、安装 Let's Encrypt 证书的 certbot。请在第 2 步绑定域名完成后进行。
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com
输入邮箱并同意条款后会自动完成设置。证书每 90 天自动续期,可以用以下命令提前确认续期是否正常。
sudo certbot renew --dry-run
遇到问题时
- 网站打不开 —— 请用
sudo systemctl status nginx确认 Nginx 是否正在运行,以及防火墙中是否开放了 80/443。 - certbot 失败 —— 大多是因为域名还没有指向服务器 IP。请先用
nslookup确认。 - 502 Bad Gateway —— 通过
proxy_pass连接的应用没有运行。请先运行应用。