温馨提示×

ubuntu apache2怎样设置

小樊
34
2026-09-14 07:51:13
栏目: 智能运维

在 Ubuntu 上配置 Apache2 通常包括:安装、启动、配置虚拟主机、设置防火墙等。下面给你一份常用、实用的操作指南(适用于 Ubuntu 20.04 / 22.04 / 24.04)。


一、安装 Apache2

sudo apt update
sudo apt install apache2 -y

安装完成后,Apache 会自动启动。


二、基本管理命令

# 启动
sudo systemctl start apache2

# 停止
sudo systemctl stop apache2

# 重启
sudo systemctl restart apache2

# 查看状态
sudo systemctl status apache2

# 开机自启
sudo systemctl enable apache2

三、测试是否成功

浏览器访问:

http://服务器IP

看到 Apache2 Ubuntu Default Page 即成功。


四、网站目录结构

默认网站根目录:

/var/www/html

默认配置文件:

/etc/apache2/sites-available/000-default.conf

主配置文件:

/etc/apache2/apache2.conf

五、配置虚拟主机(多网站)

1️⃣ 创建网站目录

sudo mkdir -p /var/www/example.com/public_html
sudo chown -R $USER:$USER /var/www/example.com

2️⃣ 创建虚拟主机配置

sudo nano /etc/apache2/sites-available/example.com.conf

内容示例:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html

    <Directory /var/www/example.com/public_html>
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

3️⃣ 启用站点

sudo a2ensite example.com.conf
sudo a2dissite 000-default.conf   # 可选:禁用默认站点

4️⃣ 启用重写模块(常用)

sudo a2enmod rewrite

5️⃣ 重启 Apache

sudo systemctl restart apache2

六、防火墙设置(UFW)

sudo ufw allow 80
sudo ufw allow 443
sudo ufw enable

查看状态:

sudo ufw status

七、配置 HTTPS(Let’s Encrypt)

sudo apt install certbot python3-certbot-apache -y
sudo certbot --apache -d example.com -d www.example.com

自动续签测试:

sudo certbot renew --dry-run

八、常见问题

❌ 403 Forbidden

  • 检查目录权限
  • 确认 Require all granted

❌ 网站不生效

  • 是否执行 a2ensite
  • 是否重启 Apache

❌ 端口被占用

sudo netstat -tulnp | grep :80

如果你有具体需求(比如:

  • 配置 PHP
  • 反向代理
  • 多域名
  • 本地开发环境
  • Docker 中运行 Apache)

可以告诉我,我可以给你更针对性的配置示例

0