温馨提示×

ubuntu apache2如何虚拟

小樊
39
2026-09-14 07:57:14
栏目: 云计算

你提到的“ubuntu apache2 如何虚拟”,通常是指 在 Ubuntu 上用 Apache2 配置虚拟主机(Virtual Host),也就是一个服务器跑多个网站。下面我给你一个最常见、最实用的做法(基于域名)。


一、前提条件

  1. 已安装 Ubuntu(20.04 / 22.04 均可)
  2. 已安装 Apache2
    sudo apt update
    sudo apt install apache2
    
  3. 有域名(或本地测试用 hosts 文件)

二、创建网站目录

假设我们要建两个站点:

  • site1.test
  • site2.test
sudo mkdir -p /var/www/site1
sudo mkdir -p /var/www/site2

echo "<h1>Site1</h1>" | sudo tee /var/www/site1/index.html
echo "<h1>Site2</h1>" | sudo tee /var/www/site2/index.html

三、创建虚拟主机配置文件

Apache 的虚拟主机文件在:

/etc/apache2/sites-available/

1️⃣ site1 配置

sudo nano /etc/apache2/sites-available/site1.conf

内容:

<VirtualHost *:80>
    ServerName site1.test
    DocumentRoot /var/www/site1

    <Directory /var/www/site1>
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/site1_error.log
    CustomLog ${APACHE_LOG_DIR}/site1_access.log combined
</VirtualHost>

2️⃣ site2 配置

sudo nano /etc/apache2/sites-available/site2.conf

内容类似,把 site1 改成 site2


四、启用站点

sudo a2ensite site1.conf
sudo a2ensite site2.conf

禁用默认站点(可选):

sudo a2dissite 000-default.conf

五、检查并重载 Apache

sudo apache2ctl configtest
sudo systemctl reload apache2

六、本地测试(无真实域名)

编辑本机 hosts 文件(Windows / macOS / Linux 都行):

127.0.0.1 site1.test
127.0.0.1 site2.test

浏览器访问:

http://site1.test
http://site2.test

七、常见问题

✅ 403 错误
→ 检查目录权限和 Require all granted

✅ 访问一直是默认页
→ 没启用站点或 ServerName 不对

✅ 想用 HTTPS
→ 用:

sudo apt install certbot python3-certbot-apache
sudo certbot --apache

如果你说的“虚拟”是:

  • 虚拟目录(Alias)
  • 虚拟用户
  • 虚拟机
  • Docker + Apache

可以告诉我,我按你具体需求写。

0