温馨提示×

apache2配置在ubuntu如何

小樊
43
2026-08-27 14:36:09
栏目: 智能运维

下面给你一个在 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 reload apache2   # 平滑重载配置

二、防火墙放行(如启用 UFW)

sudo ufw allow 'Apache Full'

验证:

sudo ufw status

三、测试 Apache 是否正常工作

浏览器访问:

http://服务器IP

看到 Apache2 Ubuntu Default Page 即成功。


四、Apache2 目录结构(重点)

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

网站根目录:

/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️⃣ 创建测试页面

nano /var/www/example.com/public_html/index.html
<h1>example.com 网站配置成功</h1>

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

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>

4️⃣ 启用站点

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

5️⃣ 重启 Apache

sudo systemctl restart apache2

六、启用 Rewrite(常见需求)

sudo a2enmod rewrite
sudo systemctl restart apache2

.htaccess 才能生效(前提是 AllowOverride All)。


七、配置 HTTPS(Let’s Encrypt)

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

自动:

  • 申请证书
  • 配置 HTTPS
  • 自动续期

八、常用排错命令

查看错误日志

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

检查配置文件语法

apache2ctl configtest

九、简单总结

功能 路径 / 命令
主配置 /etc/apache2/apache2.conf
网站配置 /etc/apache2/sites-available/
启用站点 a2ensite
启用模块 a2enmod
重启 systemctl restart apache2

如果你有具体需求(比如:PHP、反向代理、多域名、权限问题、403/404 报错),直接告诉我,我可以给你针对性的配置示例

0