在云服务器上使用 nginx 部署静态网站

云服务器

云计算厂商有很多,请读者自行选择,并根据厂商提供的帮助文档进行购买、使用。这里只提示几个关键点:云服务器,虚拟私有云 VPC,公网 IP,安全组,域名,ICP备案,公安备案。

安装与配置 nginx

笔者的安装环境:Ubuntu 24.04.1 LTS,x86_64 架构,nginx == 1.26.3

安装方式:Pre-Built Packages

具体安装步骤参考 nginx 官网:https://nginx.org/en/linux_packages.html#Ubuntu

这种安装方式的好处是,使用 apt 命令,方便解决依赖问题,并且从 nginx 官方仓库​​下载安装软件包,而不是从 Ubuntu 仓库下载。同时自动添加 nginx 命令和 nginx.service 服务。

nginx 配置文件

/etc/nginx/nginx.conf:主配置文件,不要修改
/etc/nginx/conf.d/:附加配置文件目录,里面所有 .conf 后缀的文件是不同的网站配置
/etc/nginx/conf.d/default.conf:默认的网站配置,请备份这个文件,以便后面参考这个配置创建新的配置

启停 nginx

不建议直接运行 nginx 命令,而是应该用 systemctl 启动 nginx.service 服务。

1
2
3
4
5
6
7
8
9
10
# 查看状态
systemctl status nginx
# 启动
systemctl start nginx
# 停止
systemctl stop nginx
# 重启
systemctl restart nginx
# 启动系统时,自动启动
systemctl enable nginx

使用 nginx 部署静态网站

部署网站的配置在 /etc/nginx/conf.d/,注意:其他发行版的 Linux 可能不是这个路径。

1
2
3
4
5
6
cd /etc/nginx/conf.d/
# 重命名备份,修改文件后缀,让这个 default.conf 失效
mv default.conf default.conf.back
# 使用 default.conf.back 的模板创建新的配置
cp default.conf.back your-website-name.conf
vim your-website-name.conf

your-website-name.conf 配置如下:

注意:

  • server_name 选项,如果购买了域名、且完成解析与备案,可以将 localhost 改成自己的域名
  • root 选项,不能配置 /root 下的路径,建议放在 /var/www
1
2
3
4
5
6
7
8
server {
listen 80;
server_name localhost;
location / {
root /var/www/your-website-name;
index index.html index.htm;
}
}

更新配置后,使用 systemctl 启动或重启 nginx。