温馨提示×

ubuntu上apache2如何配置

小樊
43
2026-08-27 14:26:03
栏目: 智能运维

下面给你一个在 Ubuntu 上配置 Apache2 的完整入门指南,从安装到常见配置(虚拟主机、端口、目录权限、HTTPS 等),适合大多数使用场景。


一、安装 Apache2

sudo apt update
sudo apt install apache2 -y

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

查看状态:

sudo systemctl status apache2

常用命令:

sudo systemctl start apache2
sudo systemctl stop apache2
sudo systemctl restart apache2
sudo systemctl enable apache2   # 开机自启

二、防火墙放行(如有 UFW)

sudo ufw allow 80
sudo ufw allow 443
sudo ufw reload

三、测试 Apache 是否运行

浏览器访问:

http://服务器IP

看到 Apache2 Ubuntu Default Page 即成功。


四、Apache2 目录结构说明

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

网站默认根目录:

/var/www/html

五、配置虚拟主机(推荐方式)

1️⃣ 创建网站目录

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

2️⃣ 创建虚拟主机配置文件

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

示例内容:

<VirtualHost *:80>
    ServerAdmin webmaster@example.com
    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

六、启用伪静态(URL Rewrite)

sudo a2enmod rewrite
sudo systemctl restart apache2

确保目录中:

AllowOverride All

七、配置 HTTPS(Let’s Encrypt)

1️⃣ 安装 Certbot

sudo apt install certbot python3-certbot-apache -y

2️⃣ 申请证书

sudo certbot --apache -d example.com -d www.example.com

证书会自动续签。


八、修改监听端口(如 8080)

编辑:

sudo nano /etc/apache2/ports.conf

修改:

Listen 8080

虚拟主机中:

<VirtualHost *:8080>

重启:

sudo systemctl restart apache2

九、常见排错

1️⃣ 403 Forbidden

  • 目录权限不足
  • Require all granted 未设置

2️⃣ 404 Not Found

  • DocumentRoot 路径错误
  • 文件不存在

3️⃣ 配置错误

sudo apache2ctl configtest

十、常用模块

sudo a2enmod ssl
sudo a2enmod rewrite
sudo a2enmod headers
sudo systemctl restart apache2

如果你有具体需求(如:PHP、多站点、反向代理、Laravel、内网部署、Docker),可以直接告诉我,我可以给你针对性的配置示例

0