在Ubuntu上用NGINX部署.Net API时绑定域名的方法
绑定域名到Ubuntu VPS上的.NET Core API(Nginx反向代理)
1. 配置域名DNS解析
登录你的域名注册商后台,找到DNS管理页面,添加两条A记录:
- 主机记录填
@(对应裸域名,比如yourdomain.com),记录值填写VPS的公网IP - 主机记录填
www(对应www.yourdomain.com),记录值同样填写VPS的公网IP
解析生效需要10分钟到几小时,可通过ping yourdomain.com命令验证域名是否已指向正确IP。
2. 确保.NET Core API在VPS上稳定运行
把本地的API部署到VPS后,用systemd托管服务保证API持续运行:
- 创建服务配置文件:
sudo nano /etc/systemd/system/your-api.service - 写入以下内容(替换实际的项目路径和文件名):
[Unit] Description=你的.NET Core API服务 [Service] WorkingDirectory=/var/www/your-api ExecStart=/usr/bin/dotnet /var/www/your-api/YourApi.dll Restart=always RestartSec=10 User=www-data Environment=ASPNETCORE_ENVIRONMENT=Production [Install] WantedBy=multi-user.target
- 启动服务并设置开机自启:
sudo systemctl daemon-reload sudo systemctl start your-api.service sudo systemctl enable your-api.service
验证API本地可访问:执行curl http://localhost:5000(假设API监听5000端口),能返回接口响应即为正常。
3. 配置Nginx反向代理
- 创建Nginx站点配置文件:
sudo nano /etc/nginx/sites-available/yourdomain.com - 写入反向代理规则(替换域名和API监听端口):
server { listen 80; server_name yourdomain.com www.yourdomain.com; location / { proxy_pass http://localhost:5000; # 对应API的监听端口 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; } }
- 启用该站点:
sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/ - 验证Nginx配置合法性:
sudo nginx -t - 重启Nginx生效:
sudo systemctl restart nginx
4. 配置HTTPS(强制加密访问)
现在浏览器默认要求HTTPS,用Let's Encrypt免费证书配置:
- 安装certbot及Nginx插件:
sudo apt update sudo apt install certbot python3-certbot-nginx
- 自动获取证书并配置Nginx:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
按照提示选择是否强制HTTPS跳转(建议选2,自动将HTTP请求重定向到HTTPS)。
验证证书自动续期功能:sudo certbot renew --dry-run,测试通过后证书会自动续期。
5. 测试访问
在浏览器输入https://yourdomain.com或https://www.yourdomain.com,即可直接访问你的API接口。
内容的提问来源于stack exchange,提问作者Ale Yanczuk
相关产品推荐
相关产品推荐

