Ubuntu虚拟机安装与配置Web服务器(以Apache/Nginx为例)
sudo组)。sudo apt update && sudo apt upgrade -y
Apache是Ubuntu默认的Web服务器,安装步骤如下:
sudo apt install apache2 -y
安装完成后,Apache会自动启动,可通过以下命令验证状态:
sudo systemctl status apache2
若显示“active (running)”,则表示服务已启动。
Nginx以高性能著称,适合高并发场景,安装命令如下:
sudo apt install nginx -y
同样,安装完成后启动Nginx并设置开机自启:
sudo systemctl start nginx
sudo systemctl enable nginx
验证状态:
sudo systemctl status nginx
```。
### **三、验证Web服务器运行**
安装完成后,在浏览器中输入虚拟机的**IP地址**(可通过`ip addr show`命令查看,如`192.168.92.129`),若看到以下页面则说明安装成功:
- Apache:显示“Apache2 Ubuntu Default Page”;
- Nginx:显示“Welcome to nginx!”。
### **四、配置Web服务器**
#### **1. Apache配置(虚拟主机)**
若需绑定域名或创建多个站点,需配置虚拟主机:
- 创建配置文件(以`example.com`为例):
```bash
sudo nano /etc/apache2/sites-available/example.com.conf
example.com为你的域名,/var/www/example.com为网站根目录):<VirtualHost *:80>
ServerAdmin webmaster@example.com
ServerName example.com
DocumentRoot /var/www/example.com
<Directory /var/www/example.com>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
</VirtualHost>
sudo a2ensite example.com.conf
sudo a2dissite 000-default.conf
sudo systemctl reload apache2
```。
Nginx使用“服务器块”(类似Apache的虚拟主机)处理不同域名:
sudo nano /etc/nginx/sites-available/example.com
example.com和网站根目录):server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t # 检查语法
sudo systemctl reload nginx # 重新加载配置
```。
默认网站根目录:
/var/www/html;/var/www/html(或自定义的/var/www/example.com)。将网站文件(如index.html)上传至根目录,可通过以下命令创建测试页面:
sudo nano /var/www/html/index.html
输入以下内容并保存:
<!DOCTYPE html>
<html>
<head>
<title>My Web Server</title>
</head>
<body>
<h1>Welcome to My Web Server!</h1>
</body>
</html>
刷新浏览器即可看到自定义页面。
sudo apt install ufw -y
sudo ufw allow 'Apache Full' # Apache
# 或
sudo ufw allow 'Nginx Full' # Nginx
sudo ufw enable # 启用防火墙
sudo ufw status # 查看状态
```。
sudo apt install certbot python3-certbot-apache # Apache
# 或
sudo apt install certbot python3-certbot-nginx # Nginx
sudo certbot --apache -d example.com -d www.example.com # Apache
# 或
sudo certbot --nginx -d example.com -d www.example.com # Nginx
按提示完成配置,证书会自动续期。systemctl status apache2/nginx)、防火墙是否拦截(ufw status)、IP地址是否正确(ip addr show);www-data(Apache)或www-data(Nginx),可通过sudo chown -R www-data:www-data /var/www/html修改。