温馨提示×

apache在linux如何配置

小樊
47
2026-10-29 00:43:11
栏目: 智能运维

下面给你一份Linux 下 Apache(httpd)常见配置入门指南,以 CentOS / RHEL / Ubuntu 为主,涵盖安装、启动、虚拟主机、常用配置和排错。


一、安装 Apache

CentOS / RHEL

sudo yum install httpd -y
# 或 CentOS 8+
sudo dnf install httpd -y

Ubuntu / Debian

sudo apt update
sudo apt install apache2 -y

二、启动与管理服务

CentOS / RHEL

sudo systemctl start httpd
sudo systemctl enable httpd
sudo systemctl status httpd

Ubuntu / Debian

sudo systemctl start apache2
sudo systemctl enable apache2
sudo systemctl status apache2

三、目录结构说明

CentOS

  • 主配置:/etc/httpd/conf/httpd.conf
  • 虚拟主机:/etc/httpd/conf.d/
  • 网站根目录:/var/www/html

Ubuntu

  • 主配置:/etc/apache2/apache2.conf
  • 虚拟主机:/etc/apache2/sites-available/
  • 启用站点:/etc/apache2/sites-enabled/
  • 网站根目录:/var/www/html

四、基本配置示例(修改端口 / 根目录)

编辑主配置文件:

# CentOS
vi /etc/httpd/conf/httpd.conf

# Ubuntu
vi /etc/apache2/ports.conf
vi /etc/apache2/sites-available/000-default.conf

示例修改:

Listen 8080
DocumentRoot "/data/www"
<Directory "/data/www">
    AllowOverride All
    Require all granted
</Directory>

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

CentOS

在 /etc/httpd/conf.d/ 新建文件:

vi /etc/httpd/conf.d/example.conf
<VirtualHost *:80>
    ServerName www.example.com
    DocumentRoot /var/www/example
    <Directory /var/www/example>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

重启:

systemctl restart httpd

Ubuntu

cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/example.conf
<VirtualHost *:80>
    ServerName www.example.com
    DocumentRoot /var/www/example
</VirtualHost>

启用站点:

a2ensite example.conf
systemctl restart apache2

六、开启 rewrite(伪静态)

Ubuntu

a2enmod rewrite
systemctl restart apache2

CentOS

主配置中确保:

LoadModule rewrite_module modules/mod_rewrite.so

七、防火墙与 SELinux

防火墙

# CentOS
firewall-cmd --permanent --add-service=http
firewall-cmd --reload

# Ubuntu
ufw allow 80

SELinux(CentOS)

setsebool -P httpd_can_network_connect 1
chcon -R -t httpd_sys_content_t /var/www

八、常见排错

# 查看错误日志
tail -f /var/log/httpd/error_log     # CentOS
tail -f /var/log/apache2/error.log   # Ubuntu

# 配置语法检查
httpd -t        # CentOS
apache2ctl -t   # Ubuntu

九、最小可用示例

  1. 放页面
echo "Hello Apache" > /var/www/html/index.html
  1. 浏览器访问
http://服务器IP

如果你告诉我:

  • Linux 发行版
  • 用途(静态站 / PHP / 反向代理 / HTTPS)

我可以给你一份针对性配置模板。

0 踩