温馨提示×

ubuntu apache2如何设置

小樊
33
2026-07-17 11:36:57
栏目: 智能运维

下面给你一份Ubuntu 下 Apache2 的基础设置指南,从安装到常见配置,适合新手一步一步来。


一、安装 Apache2

sudo apt update
sudo apt install apache2

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

查看状态:

sudo systemctl status apache2

常用命令:

sudo systemctl start apache2    # 启动
sudo systemctl stop apache2     # 停止
sudo systemctl restart apache2  # 重启
sudo systemctl enable apache2   # 开机自启

二、访问默认页面

在浏览器中访问服务器 IP:

http://服务器IP

看到 Apache2 Ubuntu Default Page 说明成功。


三、目录结构说明(很重要)

/etc/apache2/
├── sites-available/   # 可用站点配置
├── sites-enabled/     # 已启用站点(软链接)
├── conf-available/
├── conf-enabled/
├── mods-available/
├── mods-enabled/
├── apache2.conf       # 主配置文件
└── ports.conf         # 端口配置

网站根目录:

/var/www/html

四、配置一个网站(虚拟主机)

1️⃣ 创建网站目录

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

创建测试页面:

echo "Hello Apache" > /var/www/example.com/public_html/index.html

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 systemctl reload apache2

禁用默认站点(可选):

sudo a2dissite 000-default.conf

五、启用伪静态(.htaccess)

sudo a2enmod rewrite
sudo systemctl restart apache2

确认:

AllowOverride All

六、配置 HTTPS(Let’s Encrypt)

1️⃣ 安装 Certbot

sudo apt install certbot python3-certbot-apache

2️⃣ 申请证书

sudo certbot --apache

自动配置 HTTPS(80 → 443)。


七、常用端口说明

端口 用途
80 HTTP
443 HTTPS
8080 自定义

查看端口监听:

sudo ss -tlnp | grep apache

八、防火墙放行(UFW)

sudo ufw allow 'Apache Full'
sudo ufw reload

九、常见问题排查

❌ 403 Forbidden

  • 目录权限不对
  • Require all granted 未配置

❌ 500 Internal Server Error

sudo tail -f /var/log/apache2/error.log

❌ 站点不生效

sudo apache2ctl -S

十、快速示例总结

✅ 安装
✅ 配置虚拟主机
✅ 开启 rewrite
✅ HTTPS
✅ 日志排错


如果你有具体需求(比如:PHP、WordPress、反向代理、多站点、Docker、内网访问),直接告诉我,我可以给你定制配置示例

0