跳到主要内容

部署 Web 服务器

本教程介绍如何在 GoMami VPS 上使用 Nginx 部署一个 Web 服务器。

前置条件

  • 已部署的 VPS 实例(推荐 Ubuntu 24.04 LTS)
  • 已通过 SSH 连接 到服务器
  • 一个域名(可选,用于配置虚拟主机)

安装 Nginx

Ubuntu / Debian

# 更新软件包列表
apt update

# 安装 Nginx
apt install -y nginx

# 启动并设置开机自启
systemctl start nginx
systemctl enable nginx

# 验证运行状态
systemctl status nginx

CentOS / AlmaLinux

# 安装 Nginx
dnf install -y nginx

# 启动并设置开机自启
systemctl start nginx
systemctl enable nginx

验证安装

在浏览器中访问 http://your_server_ip,看到 Nginx 默认欢迎页面即表示安装成功。

Nginx 默认页面

配置防火墙

# UFW(Ubuntu/Debian)
ufw allow 'Nginx Full'
ufw reload

# firewalld(CentOS/AlmaLinux)
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

部署网站

基本静态网站

将网站文件放到 Nginx 默认目录:

# 默认网站根目录
ls /var/www/html/

# 创建自定义页面
cat > /var/www/html/index.html << 'EOF'
<!DOCTYPE html>
<html>
<head><title>My Website</title></head>
<body><h1>Hello from GoMami!</h1></body>
</html>
EOF

配置虚拟主机

为你的域名创建专用配置:

# 创建网站目录
mkdir -p /var/www/example.com/html

# 创建 Nginx 配置
cat > /etc/nginx/sites-available/example.com << 'EOF'
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;

location / {
try_files $uri $uri/ =404;
}
}
EOF

# 启用站点
ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

# 测试配置
nginx -t

# 重载 Nginx
systemctl reload nginx

配置 SSL 证书

使用 Let's Encrypt 免费证书:

# 安装 Certbot
apt install -y certbot python3-certbot-nginx

# 申请并自动配置证书
certbot --nginx -d example.com -d www.example.com

# 验证自动续期
certbot renew --dry-run
提示

Certbot 会自动修改 Nginx 配置以启用 HTTPS,并设置 HTTP 到 HTTPS 的自动跳转。

性能优化

/etc/nginx/nginx.conf 中调整:

worker_processes auto;

events {
worker_connections 1024;
}

http {
# 启用 Gzip 压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript;

# 客户端缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
}
# 测试并重载配置
nginx -t && systemctl reload nginx

下一步