一、安装Nginx
sudo apt update,确保系统获取最新的软件包信息。sudo apt install nginx,安装过程中按提示确认(输入Y),等待安装完成。sudo systemctl start nginx;设置开机自动启动sudo systemctl enable nginx。http://your_server_ip),若看到Nginx默认欢迎页面,说明安装成功;sudo systemctl status nginx,若显示“active (running)”,则服务正常运行。二、配置Nginx虚拟主机(站点)
example.com),并设置合理权限:sudo mkdir -p /var/www/example.com/html # 创建根目录
sudo chown -R $USER:$USER /var/www/example.com/html # 赋予用户所有权(便于后续操作)
sudo chmod -R 755 /var/www # 设置目录权限(755为推荐值)
```。
index.html,添加简单内容(如Hello World):echo "Hello World" | sudo tee /var/www/example.com/html/index.html
```。
/etc/nginx/sites-available/目录下新建配置文件(如example.com.conf):sudo nano /etc/nginx/sites-available/example.com.conf
添加以下基础配置(按需修改server_name、root等参数):server {
listen 80; # 监听HTTP端口(80)
server_name example.com www.example.com; # 域名(替换为你的域名)
root /var/www/example.com/html; # 网站根目录
index index.html index.htm; # 默认首页文件
location / {
try_files $uri $uri/ =404; # 尝试匹配请求文件,未找到则返回404
}
# 可选:记录访问日志和错误日志
access_log /var/log/nginx/example.com_access.log;
error_log /var/log/nginx/example.com_error.log;
}
```。
sites-available到sites-enabled的符号链接(Nginx仅加载sites-enabled中的配置):sudo ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/
```。
sudo nginx -t,若输出“syntax is ok”和“test is successful”,说明配置无错误。sudo systemctl reload nginx
```。
三、配置防火墙(若启用UFW) Ubuntu默认使用UFW防火墙,需允许HTTP(80端口)和HTTPS(443端口)流量:
sudo ufw allow 'Nginx Full' # 允许Nginx的全部流量(HTTP+HTTPS)
sudo ufw status # 查看防火墙状态(确认规则已添加)
```。
**四、配置HTTPS(可选,推荐)**
使用Let's Encrypt免费证书实现HTTPS加密:
1. **安装Certbot**:运行`sudo apt install certbot python3-certbot-nginx`,安装Certbot及Nginx插件。
2. **获取证书**:执行`sudo certbot --nginx -d example.com -d www.example.com`(替换为你的域名),按提示完成域名验证。
3. **自动续期**:Let's Encrypt证书有效期为90天,设置自动续期测试:
```bash
sudo certbot renew --dry-run
若测试成功,证书会在到期前自动续期。
五、常见问题解决
sudo chown -R www-data:www-data /var/www/example.com/html(Nginx默认用户为www-data);index.html或index.htm文件。sudo netstat -tulnp | grep ':80\b',查看是否有其他服务占用80端口;sudo systemctl stop apache2)或修改Nginx监听端口(修改listen指令)。nginx -t输出的错误信息,定位配置文件中的语法问题(如括号不匹配、指令拼写错误)。