温馨提示×

如何Ubuntu配Apache2

小樊
44
2026-10-11 03:15:38
栏目: 智能运维

下面给你一份在 Ubuntu 上配置 Apache2 的实用指南,从安装到常见配置,适合新手和日常使用。


一、安装 Apache2

sudo apt update
sudo apt install apache2 -y

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

查看状态:

sudo systemctl status apache2

若未启动:

sudo systemctl start apache2
sudo systemctl enable apache2

二、防火墙设置(如有 UFW)

sudo ufw allow 'Apache Full'

测试访问:

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

2. 写测试页面

echo "<h1>Hello Apache2</h1>" | sudo tee /var/www/example.com/public_html/index.html

3. 设置权限

sudo chown -R www-data:www-data /var/www/example.com
sudo chmod -R 755 /var/www

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

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>

启用站点:

sudo a2ensite example.com.conf
sudo a2dissite 000-default.conf

重启 Apache:

sudo systemctl reload apache2

六、启用 rewrite(常用)

sudo a2enmod rewrite
sudo systemctl restart apache2

七、启用 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

八、常用命令速查

sudo systemctl start apache2
sudo systemctl stop apache2
sudo systemctl restart apache2
sudo systemctl reload apache2
sudo apache2ctl configtest

如果你有具体需求(比如 PHP、WordPress、反向代理、多站点、局域网访问),可以告诉我,我可以直接给你对应配置。

0 踩