教程 rockylinux tutorial

Web 服务(Apache/Nginx)

Web 服务器是托管网站和 Web 应用程序的关键组件。在 Rocky Linux 中,Apache HTTP Server 和 Nginx 是最常用的两种 Web 服务器。本教程将详细介绍如何在 Rocky Linux 系统上安装、配置和管理这两种流行的 Web 服务器。

Apache HTTP Server

Apache HTTP Server(简称 Apache)是世界上使用最广泛的 Web 服务器之一,以其稳定性、灵活性和丰富的功能集而著称。

安装 Apache

bash
# 安装 Apache
sudo dnf install httpd -y

# 启动 Apache 服务
sudo systemctl start httpd

# 设置 Apache 开机自启
sudo systemctl enable httpd

# 检查 Apache 服务状态
sudo systemctl status httpd

配置防火墙

bash
# 允许 HTTP 流量通过防火墙
sudo firewall-cmd --permanent --add-service=http

# 允许 HTTPS 流量通过防火墙
sudo firewall-cmd --permanent --add-service=https

# 重新加载防火墙规则
sudo firewall-cmd --reload

验证 Apache 安装

在浏览器中访问服务器的 IP 地址或域名,应该能看到 Apache 的默认欢迎页面:

代码
http://your_server_ip

或者使用命令行验证:

bash
curl http://localhost

Apache 配置文件结构

Apache 的主要配置文件位于 /etc/httpd/ 目录下:

  • /etc/httpd/conf/httpd.conf - 主配置文件
  • /etc/httpd/conf.d/ - 额外配置文件目录
  • /etc/httpd/conf.modules.d/ - 模块配置目录

基本配置修改

编辑主配置文件:

bash
sudo vim /etc/httpd/conf/httpd.conf

常用配置项:

代码
# 服务器根目录
ServerRoot "/etc/httpd"

# 监听端口
Listen 80

# 管理员邮箱
ServerAdmin root@localhost

# 默认网站根目录
DocumentRoot "/var/www/html"

# 目录访问控制
<Directory "/var/www/html">
    AllowOverride None
    Require all granted
</Directory>

虚拟主机配置

虚拟主机允许在单个服务器上托管多个网站。

bash
# 创建虚拟主机配置文件
sudo vim /etc/httpd/conf.d/example.com.conf

基本虚拟主机配置:

apache
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html
    ErrorLog /var/www/example.com/logs/error.log
    CustomLog /var/www/example.com/logs/access.log combined

    <Directory /var/www/example.com/public_html>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

创建必要的目录结构:

bash
# 创建网站目录
sudo mkdir -p /var/www/example.com/public_html

# 创建日志目录
sudo mkdir -p /var/www/example.com/logs

# 设置目录权限
sudo chown -R apache:apache /var/www/example.com

# 创建测试页面
echo "<h1>Welcome to example.com</h1>" | sudo tee /var/www/example.com/public_html/index.html

重新加载 Apache 配置:

bash
sudo systemctl reload httpd

Apache 模块管理

bash
# 列出已启用的模块
sudo httpd -M

# 启用模块(编辑对应配置文件)
sudo vim /etc/httpd/conf.modules.d/00-base.conf

常用模块:

  • mod_rewrite - URL 重写
  • mod_ssl - HTTPS 支持
  • mod_deflate - 内容压缩
  • mod_headers - HTTP 头管理
  • mod_status - 服务器状态页面

Apache 日志文件

Apache 的日志文件位于 /var/log/httpd/ 目录下:

  • access.log - 访问日志
  • error.log - 错误日志

查看日志:

bash
# 查看错误日志
sudo tail -f /var/log/httpd/error.log

# 查看访问日志
sudo tail -f /var/log/httpd/access.log

配置 HTTPS

安装 SSL 证书(使用自签名证书作为示例):

bash
# 安装 mod_ssl 模块
sudo dnf install mod_ssl -y

# 创建自签名证书
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/pki/tls/private/example.com.key -out /etc/pki/tls/certs/example.com.crt

配置 SSL 虚拟主机:

bash
sudo vim /etc/httpd/conf.d/ssl.conf

或创建专用配置文件:

bash
sudo vim /etc/httpd/conf.d/example.com-ssl.conf

SSL 虚拟主机配置:

apache
<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/example.com/public_html

    SSLEngine on
    SSLCertificateFile /etc/pki/tls/certs/example.com.crt
    SSLCertificateKeyFile /etc/pki/tls/private/example.com.key

    ErrorLog /var/www/example.com/logs/ssl_error.log
    CustomLog /var/www/example.com/logs/ssl_access.log combined

    <Directory /var/www/example.com/public_html>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

重定向 HTTP 到 HTTPS:

apache
<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / https://example.com/
</VirtualHost>

重启 Apache 服务:

bash
sudo systemctl restart httpd

Nginx

Nginx(发音为 “engine x”)是一款高性能的 HTTP 和反向代理服务器,以其稳定性、丰富的功能集、低资源消耗和高并发处理能力而闻名。

安装 Nginx

bash
# 安装 Nginx
sudo dnf install nginx -y

# 启动 Nginx 服务
sudo systemctl start nginx

# 设置 Nginx 开机自启
sudo systemctl enable nginx

# 检查 Nginx 服务状态
sudo systemctl status nginx

配置防火墙

bash
# 允许 HTTP 流量通过防火墙
sudo firewall-cmd --permanent --add-service=http

# 允许 HTTPS 流量通过防火墙
sudo firewall-cmd --permanent --add-service=https

# 重新加载防火墙规则
sudo firewall-cmd --reload

验证 Nginx 安装

在浏览器中访问服务器的 IP 地址或域名,应该能看到 Nginx 的默认欢迎页面:

代码
http://your_server_ip

或者使用命令行验证:

bash
curl http://localhost

Nginx 配置文件结构

Nginx 的主要配置文件位于 /etc/nginx/ 目录下:

  • /etc/nginx/nginx.conf - 主配置文件
  • /etc/nginx/conf.d/ - 服务器块配置目录
  • /etc/nginx/default.d/ - 默认服务器配置目录

基本配置修改

编辑主配置文件:

bash
sudo vim /etc/nginx/nginx.conf

常用配置项:

nginx
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    include /etc/nginx/conf.d/*.conf;
}

服务器块配置

Nginx 使用服务器块(相当于 Apache 的虚拟主机)来托管多个网站。

bash
# 创建服务器块配置文件
sudo vim /etc/nginx/conf.d/example.com.conf

基本服务器块配置:

nginx
server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example.com/public_html;
    index index.html index.htm index.php;

    location / {
        try_files $uri $uri/ =404;
    }

    error_log /var/log/nginx/example.com_error.log;
    access_log /var/log/nginx/example.com_access.log;
}

创建必要的目录结构:

bash
# 创建网站目录
sudo mkdir -p /var/www/example.com/public_html

# 设置目录权限
sudo chown -R nginx:nginx /var/www/example.com

# 创建测试页面
echo "<h1>Welcome to example.com</h1>" | sudo tee /var/www/example.com/public_html/index.html

测试并重新加载 Nginx 配置:

bash
# 测试配置语法
sudo nginx -t

# 重新加载配置
sudo systemctl reload nginx

Nginx 模块管理

Nginx 使用动态和静态模块,大多数常用模块已包含在默认安装中。

bash
# 查看已编译的模块
sudo nginx -V

Nginx 日志文件

Nginx 的日志文件位于 /var/log/nginx/ 目录下:

  • access.log - 访问日志
  • error.log - 错误日志

查看日志:

bash
# 查看错误日志
sudo tail -f /var/log/nginx/error.log

# 查看访问日志
sudo tail -f /var/log/nginx/access.log

配置 HTTPS

安装 SSL 证书(使用自签名证书作为示例):

bash
# 创建自签名证书
sudo mkdir -p /etc/nginx/ssl
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/example.com.key -out /etc/nginx/ssl/example.com.crt

配置 SSL 服务器块:

bash
sudo vim /etc/nginx/conf.d/example.com.conf

SSL 服务器块配置:

nginx
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com www.example.com;

    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    root /var/www/example.com/public_html;
    index index.html index.htm index.php;

    location / {
        try_files $uri $uri/ =404;
    }

    error_log /var/log/nginx/example.com_ssl_error.log;
    access_log /var/log/nginx/example.com_ssl_access.log;
}

测试并重新加载 Nginx 配置:

bash
# 测试配置语法
sudo nginx -t

# 重新加载配置
sudo systemctl reload nginx

配置 PHP 支持

Apache 配置 PHP

安装 PHP 和相关模块:

bash
# 安装 PHP 和常用模块
sudo dnf install php php-mysqlnd php-fpm php-gd php-mbstring php-xml php-json -y

# 安装 PHP-FPM(FastCGI Process Manager)
sudo dnf install php-fpm -y

# 启动 PHP-FPM 服务
sudo systemctl start php-fpm
sudo systemctl enable php-fpm

配置 Apache 与 PHP-FPM 配合:

bash
# 编辑 Apache 配置文件以使用 PHP-FPM
sudo vim /etc/httpd/conf.d/php-fpm.conf

添加以下内容:

apache
<FilesMatch \.php$>
    SetHandler "proxy:unix:/run/php-fpm/www.sock|fcgi://localhost"
</FilesMatch>

配置 PHP-FPM:

bash
sudo vim /etc/php-fpm.d/www.conf

确保以下设置正确:

代码
user = apache
group = apache
listen = /run/php-fpm/www.sock
listen.owner = apache
listen.group = apache

重启服务:

bash
sudo systemctl restart php-fpm
sudo systemctl restart httpd

Nginx 配置 PHP

安装 PHP 和相关模块:

bash
# 安装 PHP 和常用模块
sudo dnf install php php-mysqlnd php-fpm php-gd php-mbstring php-xml php-json -y

配置 PHP-FPM:

bash
sudo vim /etc/php-fpm.d/www.conf

修改用户和组为 nginx:

代码
user = nginx
group = nginx
listen = /run/php-fpm/www.sock
listen.owner = nginx
listen.group = nginx

启动 PHP-FPM 服务:

bash
sudo systemctl start php-fpm
sudo systemctl enable php-fpm

配置 Nginx 处理 PHP 文件:

bash
sudo vim /etc/nginx/conf.d/example.com.conf

更新服务器块配置:

nginx
server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example.com/public_html;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/run/php-fpm/www.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    error_log /var/log/nginx/example.com_error.log;
    access_log /var/log/nginx/example.com_access.log;
}

测试并重新加载 Nginx 配置:

bash
# 测试配置语法
sudo nginx -t

# 重新加载配置
sudo systemctl reload nginx

性能优化

Apache 性能优化

编辑 Apache 配置文件:

bash
sudo vim /etc/httpd/conf.modules.d/00-mpm.conf

调整 MPM(多处理模块)设置:

apache
# 对于 prefork 模块(默认)
<IfModule mpm_prefork_module>
    StartServers         5
    MinSpareServers      5
    MaxSpareServers     10
    MaxRequestWorkers   150
    MaxConnectionsPerChild   0
</IfModule>

# 对于 event 模块(推荐用于高流量网站)
<IfModule mpm_event_module>
    StartServers         2
    ServerLimit         16
    MinSpareThreads     25
    MaxSpareThreads     75
    ThreadsPerChild     25
    MaxRequestWorkers   400
    MaxConnectionsPerChild   0
</IfModule>

启用压缩:

bash
sudo vim /etc/httpd/conf.d/compress.conf

添加以下内容:

apache
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>

Nginx 性能优化

编辑 Nginx 主配置文件:

bash
sudo vim /etc/nginx/nginx.conf

调整工作进程和连接设置:

nginx
user nginx;
worker_processes auto;  # 自动设置为 CPU 核心数
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 4096;  # 每个工作进程的最大连接数
    multi_accept on;  # 尽可能多地接受新连接
    use epoll;  # 使用 epoll 事件驱动模型
}

http {
    # 其他配置...

    # 压缩设置
    gzip on;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    # 缓存设置
    open_file_cache max=100000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # 超时设置
    keepalive_timeout 65;
    send_timeout 10;

    # 缓冲区设置
    client_body_buffer_size 128k;
    client_max_body_size 10m;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 4k;
    output_buffers 1 32k;
    postpone_output 1460;
}

安全加固

Apache 安全加固

  1. 隐藏版本信息:
bash
sudo vim /etc/httpd/conf/httpd.conf

添加以下内容:

apache
ServerTokens Prod
ServerSignature Off
  1. 禁用不必要的模块:
bash
# 查看已启用的模块
sudo httpd -M

# 编辑模块配置文件,注释掉不需要的模块
sudo vim /etc/httpd/conf.modules.d/00-base.conf
  1. 启用 mod_security:
bash
# 安装 mod_security
sudo dnf install mod_security mod_security_crs -y

# 配置 mod_security
sudo cp /etc/httpd/conf.d/mod_security.conf.rpmnew /etc/httpd/conf.d/mod_security.conf

sudo systemctl restart httpd

Nginx 安全加固

  1. 隐藏版本信息:
bash
sudo vim /etc/nginx/nginx.conf

在 http 块中添加:

nginx
server_tokens off;
  1. 限制请求大小:

在 http 块或 server 块中添加:

nginx
client_max_body_size 10m;
  1. 设置适当的内容安全策略:

在 server 块中添加:

nginx
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options SAMEORIGIN;
add_header X-XSS-Protection "1; mode=block";
  1. 禁用不必要的 HTTP 方法:
nginx
location / {
    # 其他配置...
    limit_except GET POST HEAD {
        deny all;
    }
}

监控和维护

Apache 监控

  1. 启用服务器状态页面:
bash
sudo vim /etc/httpd/conf.d/status.conf

添加以下内容:

apache
<Location /server-status>
    SetHandler server-status
    Require local
    # 允许特定 IP 访问
    # Require ip 192.168.1.0/24
</Location>

重启 Apache:

bash
sudo systemctl restart httpd

访问状态页面:http://your_server_ip/server-status

  1. 日志分析工具:
bash
# 安装 awstats
sudo dnf install awstats -y

# 配置 awstats
# 请参考 awstats 文档进行详细配置

Nginx 监控

  1. 启用 stub_status 模块:
bash
sudo vim /etc/nginx/conf.d/status.conf

添加以下内容:

nginx
server {
    listen 127.0.0.1:80;
    server_name localhost;

    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }
}

测试并重新加载 Nginx:

bash
sudo nginx -t
sudo systemctl reload nginx

检查状态:

bash
curl http://localhost/nginx_status
  1. 日志分析:
bash
# 安装 goaccess
sudo dnf install goaccess -y

# 分析访问日志
goaccess /var/log/nginx/access.log -o /var/www/html/report.html --log-format=COMBINED

常见问题排查

Apache 常见问题

  1. 服务无法启动:
bash
# 检查错误日志
sudo tail -f /var/log/httpd/error.log

# 检查配置语法
sudo httpd -t
  1. 403 Forbidden 错误:
  • 检查文件和目录权限
  • 确保 SELinux 上下文正确
  • 检查 Apache 配置中的访问控制
bash
# 检查 SELinux 上下文
sudo ls -Z /var/www/example.com/public_html/

# 修复 SELinux 上下文
sudo restorecon -Rv /var/www/
  1. PHP 文件下载而非执行:
  • 确保 PHP 模块正确加载
  • 检查文件处理器配置

Nginx 常见问题

  1. 服务无法启动:
bash
# 检查错误日志
sudo tail -f /var/log/nginx/error.log

# 检查配置语法
sudo nginx -t
  1. 502 Bad Gateway 错误:
  • 检查上游服务器是否运行
  • 检查 PHP-FPM 是否启动
  • 检查套接字权限
bash
# 检查 PHP-FPM 状态
sudo systemctl status php-fpm

# 检查套接字权限
sudo ls -la /run/php-fpm/
  1. 403 Forbidden 错误:
  • 检查文件和目录权限
  • 确保 SELinux 上下文正确
  • 检查 Nginx 配置中的访问控制

总结

本教程详细介绍了在 Rocky Linux 系统上安装、配置和管理 Apache HTTP Server 和 Nginx 的方法。两种服务器都提供了强大的 Web 托管功能,但各有特点:

  • Apache:配置简单直观,模块丰富,适合各种网站类型,尤其是需要 .htaccess 文件的应用。
  • Nginx:性能优异,资源消耗低,并发处理能力强,特别适合高流量网站和作为反向代理。

在实际应用中,可以根据具体需求选择合适的 Web 服务器。无论选择哪种服务器,都应关注性能优化和安全加固,定期备份配置和数据,并建立监控机制以便及时发现和解决问题。