配置CentOS上的Apache HTTP服务器的操作步骤

35 阅读2分钟

配置Apache HTTP服务器是一个涉及到多个步骤的过程,包括安装软件、配置网络设置、配置网站内容和确保安全性等。以下是在基于CentOS操作系统上配置Apache HTTP服务器的详尽步骤:

安装Apache服务器

  1. 更新系统包列表

    sudo yum update
  2. 安装Apache

    sudo yum install httpd
    ​
    
  3. 启动Apache服务

    sudo systemctl start httpd
    ​
    
  4. 设置Apache随系统启动

    sudo systemctl enable httpd
    ​
    

配置防火墙

  1. 开放HTTP和HTTPS端口

    sudo firewall-cmd --permanent --zone=public --add-service=http
    sudo firewall-cmd --permanent --zone=public --add-service=https
    ​
    
  2. 重新载入防火墙设置

    sudo firewall-cmd --reload

测试Apache服务器

  1. 在Web浏览器中查看默认欢迎页面:输入服务器IP或者在浏览器中访问 http://localhost

配置Apache虚拟主机

  1. 创建一个新的配置文件

    sudo vi /etc/httpd/conf.d/example.com.conf
    ​
    
  2. 添加以下虚拟主机配置

    <VirtualHost *:80>
        ServerAdmin webmaster@example.com
        DocumentRoot /var/www/html/example.com/public_html
        ServerName example.com
        ServerAlias www.example.com
        ErrorLog /var/www/html/example.com/logs/error.log
        CustomLog /var/www/html/example.com/logs/requests.log combined
    </VirtualHost>
    ​
    
  3. 创建网站目录和日志文件夹

    sudo mkdir -p /var/www/html/example.com/public_html
    sudo mkdir -p /var/www/html/example.com/logs
    ​
    
  4. 设置所有权和权限

    sudo chown -R $USER:$USER /var/www/html/example.com/public_html
    sudo chmod -R 755 /var/www
    ​
    
  5. 重启Apache服务

    sudo systemctl restart httpd
    ​
    

配置安全设置

  1. 安装mod_ssl以支持HTTPS

    sudo yum install mod_ssl
    ​
    
  2. 生成SSL证书(假设您使用Let's Encrypt):

    sudo yum install certbot python2-certbot-apache
    sudo certbot --apache -d example.com -d www.example.com
  3. 编辑SSL配置,调整SSL设置以提高安全性

    sudo vi /etc/httpd/conf.d/ssl.conf
    ​
    

    在该文件中,您可以配置SSL协议、加密套件等。

配置.htaccess和mod_rewrite

  1. 允许使用.htaccess文件

    编辑虚拟主机配置文件:

    sudo vi /etc/httpd/conf.d/example.com.conf
    ​
    

    并添加或修改以下行:

    <Directory "/var/www/html/example.com/public_html">
        AllowOverride All
    </Directory>
    ​
    
  2. 启用mod_rewrite模块(通常默认启动):

    sudo systemctl restart httpd
    ​
    
  3. 创建.htaccess文件

    sudo vi /var/www/html/example.com/public_html/.htaccess

    添加重写规则:

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]
    ​
    

进行性能优化

  1. 开启KeepAlive

    sudo vi /etc/httpd/conf/httpd.conf
    ​
    

    找到 KeepAlive指令,确保其设置为 On

  2. 配置KeepAliveTimeout

    适当修改Timeout值提高连接效率。

管理和监控Apache服务

  1. 监控服务状态

    systemctl status httpd
    ​
    
  2. 查看访问日志错误日志

    一般位于 /var/log/httpd/access_log和 /var/log/httpd/error_log

通过以上步骤,可实现对CentOS上Apache服务器的基本配置和管理。配置文件的编辑和系统