|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
1. 引言
Red Hat Enterprise Linux (RHEL) 是企业级应用中最受欢迎的Linux发行版之一,以其稳定性、安全性和长期支持而闻名。在企业环境中搭建Web服务器是一项关键任务,需要仔细规划和执行。本指南将详细介绍如何在RHEL系统上从零开始部署企业级Web服务器,包括基础安装、配置、安全加固、性能优化以及故障排除等全方位内容。
本指南适用于系统管理员、DevOps工程师以及任何负责在RHEL上部署和维护Web服务器的IT专业人员。我们将涵盖Apache和Nginx两种主流Web服务器的部署,并提供实际场景中的最佳实践。
2. RHEL系统安装和准备
2.1 系统要求
在开始安装之前,确保您的硬件满足以下最低要求:
• CPU: 2核心或更高
• 内存: 4GB RAM或更高(推荐8GB以上)
• 硬盘空间: 至少20GB可用空间
• 网络: 稳定的网络连接
2.2 RHEL安装步骤
1. 获取RHEL安装镜像
从Red Hat官方网站下载最新的RHEL安装ISO镜像。您需要有有效的Red Hat订阅才能下载和获取更新。
1. 创建安装介质
使用以下命令创建USB启动盘(假设USB设备为/dev/sdb):
- dd if=rhel-8.4-x86_64-dvd.iso of=/dev/sdb bs=4M status=progress
复制代码
1. 启动安装程序
从USB启动盘启动计算机,选择”Install Red Hat Enterprise Linux”选项。
1. 安装配置语言选择:选择您偏好的语言安装位置:配置磁盘分区,推荐使用自动分区网络和主机名:配置网络连接和设置主机名安全策略:根据企业安全要求选择适当的配置文件软件选择:选择”Server with GUI”或”Minimal Install”(推荐Minimal Install以减少资源占用)
2. 语言选择:选择您偏好的语言
3. 安装位置:配置磁盘分区,推荐使用自动分区
4. 网络和主机名:配置网络连接和设置主机名
5. 安全策略:根据企业安全要求选择适当的配置文件
6. 软件选择:选择”Server with GUI”或”Minimal Install”(推荐Minimal Install以减少资源占用)
7. 创建用户和设置root密码
安装配置
• 语言选择:选择您偏好的语言
• 安装位置:配置磁盘分区,推荐使用自动分区
• 网络和主机名:配置网络连接和设置主机名
• 安全策略:根据企业安全要求选择适当的配置文件
• 软件选择:选择”Server with GUI”或”Minimal Install”(推荐Minimal Install以减少资源占用)
创建用户和设置root密码
创建管理员用户并设置强密码。确保root密码足够复杂,符合企业安全策略。
1. 完成安装
完成所有配置后,开始安装过程。安装完成后,系统将提示您重启。
2.3 系统初始化配置
1. 注册系统和订阅
安装完成后,首先需要注册系统并激活订阅:
- subscription-manager register --username=your_username --password=your_password
- subscription-manager attach --auto
复制代码
1. 系统更新
更新系统到最新版本:
1. 安装常用工具
安装系统管理和故障排除所需的常用工具:
- yum install -y vim wget curl net-tools telnet bind-utils
复制代码
1. 配置防火墙
启动并配置防火墙:
- systemctl enable --now firewalld
- firewall-cmd --permanent --add-service=http
- firewall-cmd --permanent --add-service=https
- firewall-cmd --reload
复制代码
1. 禁用SELinux(可选,不推荐生产环境)
如果需要临时禁用SELinux(不推荐生产环境使用):
永久禁用需要编辑/etc/selinux/config文件,将SELINUX=enforcing改为SELINUX=disabled。
3. Web服务器选择和安装
3.1 Apache HTTP Server (httpd)
Apache是最流行的Web服务器软件之一,以其稳定性和灵活性著称。
- systemctl start httpd
- systemctl enable httpd
复制代码
检查Apache服务状态:
在浏览器中访问服务器的IP地址,您应该能看到Apache的默认欢迎页面。
Apache的主配置文件位于/etc/httpd/conf/httpd.conf。以下是几个重要的配置项:
- # 服务器根目录
- ServerRoot "/etc/httpd"
- # 监听端口
- Listen 80
- # 服务器管理员邮箱
- ServerAdmin root@localhost
- # 服务器主机名
- ServerName www.example.com:80
- # 网站文件根目录
- DocumentRoot "/var/www/html"
- # 错误日志位置
- ErrorLog "logs/error_log"
- # 访问日志位置
- CustomLog "logs/access_log" combined
复制代码
3.2 Nginx
Nginx是另一个流行的Web服务器,以其高性能和低内存消耗而闻名,特别适合高并发场景。
首先,安装EPEL仓库:
- yum install -y epel-release
复制代码
然后安装Nginx:
- systemctl start nginx
- systemctl enable nginx
复制代码
检查Nginx服务状态:
在浏览器中访问服务器的IP地址,您应该能看到Nginx的默认欢迎页面。
Nginx的主配置文件位于/etc/nginx/nginx.conf。以下是几个重要的配置项:
- # 运行用户
- user nginx;
- # 工作进程数(通常设置为CPU核心数)
- worker_processes auto;
- # 错误日志位置
- error_log /var/log/nginx/error.log;
- # 主进程PID位置
- pid /run/nginx.pid;
- # 工作模式及连接数上限
- events {
- worker_connections 1024;
- }
- # HTTP服务器配置
- 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;
- # 基本服务器配置
- server {
- listen 80 default_server;
- listen [::]:80 default_server;
- server_name _;
- root /usr/share/nginx/html;
- # 加载默认配置
- include /etc/nginx/default.d/*.conf;
- location / {
- }
- # 错误页面
- error_page 404 /404.html;
- location = /40x.html {
- }
- error_page 500 502 503 504 /50x.html;
- location = /50x.html {
- }
- }
- }
复制代码
4. 基本配置和虚拟主机设置
4.1 Apache虚拟主机配置
虚拟主机允许您在同一台服务器上托管多个网站。以下是Apache中配置基于名称的虚拟主机的步骤:
1. 创建网站目录
为每个网站创建目录:
- mkdir -p /var/www/example1.com
- mkdir -p /var/www/example2.com
复制代码
1. 创建测试页面
为每个网站创建测试页面:
- echo "<h1>Welcome to Example1.com</h1>" > /var/www/example1.com/index.html
- echo "<h1>Welcome to Example2.com</h1>" > /var/www/example2.com/index.html
复制代码
1. 设置正确的权限
- chown -R apache:apache /var/www/example1.com
- chown -R apache:apache /var/www/example2.com
- chmod -R 755 /var/www
复制代码
1. 创建虚拟主机配置文件
为每个网站创建虚拟主机配置文件:
- vim /etc/httpd/conf.d/example1.com.conf
复制代码
添加以下内容:
- <VirtualHost *:80>
- ServerName www.example1.com
- ServerAlias example1.com
- DocumentRoot /var/www/example1.com
- ErrorLog /var/log/httpd/example1.com-error.log
- CustomLog /var/log/httpd/example1.com-access.log combined
- </VirtualHost>
复制代码
创建第二个虚拟主机配置文件:
- vim /etc/httpd/conf.d/example2.com.conf
复制代码
添加以下内容:
- <VirtualHost *:80>
- ServerName www.example2.com
- ServerAlias example2.com
- DocumentRoot /var/www/example2.com
- ErrorLog /var/log/httpd/example2.com-error.log
- CustomLog /var/log/httpd/example2.com-access.log combined
- </VirtualHost>
复制代码
1. 测试配置并重启Apache
- httpd -t
- systemctl restart httpd
复制代码
4.2 Nginx虚拟主机配置
在Nginx中配置虚拟主机的步骤如下:
1. 创建网站目录
为每个网站创建目录:
- mkdir -p /var/www/example1.com
- mkdir -p /var/www/example2.com
复制代码
1. 创建测试页面
为每个网站创建测试页面:
- echo "<h1>Welcome to Example1.com</h1>" > /var/www/example1.com/index.html
- echo "<h1>Welcome to Example2.com</h1>" > /var/www/example2.com/index.html
复制代码
1. 设置正确的权限
- chown -R nginx:nginx /var/www/example1.com
- chown -R nginx:nginx /var/www/example2.com
- chmod -R 755 /var/www
复制代码
1. 创建虚拟主机配置文件
为每个网站创建虚拟主机配置文件:
- vim /etc/nginx/conf.d/example1.com.conf
复制代码
添加以下内容:
- server {
- listen 80;
- server_name example1.com www.example1.com;
- root /var/www/example1.com;
- index index.html;
- location / {
- try_files $uri $uri/ =404;
- }
- access_log /var/log/nginx/example1.com-access.log;
- error_log /var/log/nginx/example1.com-error.log;
- }
复制代码
创建第二个虚拟主机配置文件:
- vim /etc/nginx/conf.d/example2.com.conf
复制代码
添加以下内容:
- server {
- listen 80;
- server_name example2.com www.example2.com;
- root /var/www/example2.com;
- index index.html;
- location / {
- try_files $uri $uri/ =404;
- }
- access_log /var/log/nginx/example2.com-access.log;
- error_log /var/log/nginx/example2.com-error.log;
- }
复制代码
1. 测试配置并重启Nginx
- nginx -t
- systemctl restart nginx
复制代码
5. 数据库集成
5.1 MySQL/MariaDB安装和配置
MariaDB是MySQL的一个分支,在RHEL中作为默认的MySQL替代品。
- yum install -y mariadb-server mariadb
复制代码- systemctl start mariadb
- systemctl enable mariadb
复制代码
运行安全配置脚本:
- mysql_secure_installation
复制代码
按照提示设置root密码,移除匿名用户,禁止root远程登录,移除测试数据库并重新加载权限表。
登录MariaDB:
创建数据库和用户:
- CREATE DATABASE exampledb;
- CREATE USER 'exampleuser'@'localhost' IDENTIFIED BY 'strongpassword';
- GRANT ALL PRIVILEGES ON exampledb.* TO 'exampleuser'@'localhost';
- FLUSH PRIVILEGES;
- EXIT;
复制代码
5.2 PostgreSQL安装和配置
PostgreSQL是一个功能强大的开源对象关系数据库系统。
- yum install -y postgresql-server postgresql-contrib
复制代码- systemctl start postgresql
- systemctl enable postgresql
复制代码- su - postgres
- psql -c "ALTER USER postgres WITH PASSWORD 'strongpassword';"
- exit
复制代码- su - postgres
- createdb exampledb
- createuser -P exampleuser
- psql
复制代码
在psql shell中:
- GRANT ALL PRIVILEGES ON DATABASE exampledb TO exampleuser;
- \q
- exit
复制代码
5.3 与Web服务器集成
安装PHP和MySQL扩展:
- yum install -y php php-mysqlnd
复制代码
创建测试PHP文件:
- vim /var/www/html/testdb.php
复制代码
添加以下内容:
- <?php
- $servername = "localhost";
- $username = "exampleuser";
- $password = "strongpassword";
- $dbname = "exampledb";
- // 创建连接
- $conn = new mysqli($servername, $username, $password, $dbname);
- // 检查连接
- if ($conn->connect_error) {
- die("连接失败: " . $conn->connect_error);
- }
- echo "连接成功";
- $conn->close();
- ?>
复制代码
安装PHP和PostgreSQL扩展:
- yum install -y php php-pgsql
复制代码
创建测试PHP文件:
- vim /var/www/html/testdb.php
复制代码
添加以下内容:
- <?php
- $host = "localhost";
- $user = "exampleuser";
- $pass = "strongpassword";
- $db = "exampledb";
- // 创建连接
- $conn = pg_connect("host=$host dbname=$db user=$user password=$pass");
- // 检查连接
- if (!$conn) {
- die("连接失败: " . pg_last_error());
- }
- echo "连接成功";
- pg_close($conn);
- ?>
复制代码
6. 动态内容支持
6.1 PHP支持
- yum install -y php php-cli php-common
复制代码- yum install -y php-mysqlnd php-gd php-xml php-mbstring php-json php-opcache
复制代码
编辑PHP配置文件:
一些重要的配置项:
- ; 最大执行时间
- max_execution_time = 30
- ; 最大输入时间
- max_input_time = 60
- ; 内存限制
- memory_limit = 256M
- ; 上传文件最大大小
- upload_max_filesize = 64M
- ; POST数据最大大小
- post_max_size = 64M
- ; 显示错误(开发环境启用,生产环境禁用)
- display_errors = Off
- ; 日志错误
- log_errors = On
- ; 错误日志路径
- error_log = /var/log/php/error.log
复制代码
创建PHP日志目录并设置权限:
- mkdir -p /var/log/php
- chown apache:apache /var/log/php
复制代码
创建测试文件:
- vim /var/www/html/info.php
复制代码
添加以下内容:
在浏览器中访问http://your_server_ip/info.php,您应该能看到PHP配置信息。
6.2 Python支持
- yum install -y python3 python3-pip python3-devel
复制代码
创建应用目录和文件:
- mkdir -p /var/www/flaskapp
- vim /var/www/flaskapp/app.py
复制代码
添加以下内容:
- from flask import Flask
- app = Flask(__name__)
- @app.route('/')
- def hello_world():
- return 'Hello, World!'
- if __name__ == '__main__':
- app.run()
复制代码
安装mod_wsgi:
创建WSGI配置文件:
- vim /var/www/flaskapp/flaskapp.wsgi
复制代码
添加以下内容:
- #!/usr/bin/python3
- import sys
- import logging
- logging.basicConfig(stream=sys.stderr)
- sys.path.insert(0,"/var/www/flaskapp")
- from app import app as application
复制代码
创建Apache虚拟主机配置:
- vim /etc/httpd/conf.d/flaskapp.conf
复制代码
添加以下内容:
- <VirtualHost *:80>
- ServerName flaskapp.example.com
- DocumentRoot /var/www/flaskapp
- <Directory /var/www/flaskapp>
- Require all granted
- </Directory>
- WSGIDaemonProcess flaskapp python-path=/var/www/flaskapp python-home=/usr
- WSGIProcessGroup flaskapp
- WSGIScriptAlias / /var/www/flaskapp/flaskapp.wsgi
- ErrorLog /var/log/httpd/flaskapp-error.log
- CustomLog /var/log/httpd/flaskapp-access.log combined
- </VirtualHost>
复制代码
重启Apache服务:
6.3 Node.js支持
使用NodeSource仓库安装最新的Node.js版本:
- curl -sL https://rpm.nodesource.com/setup_14.x | bash -
- yum install -y nodejs
复制代码
创建应用目录和文件:
- mkdir -p /var/www/nodeapp
- vim /var/www/nodeapp/app.js
复制代码
添加以下内容:
- const http = require('http');
- const hostname = '127.0.0.1';
- const port = 3000;
- const server = http.createServer((req, res) => {
- res.statusCode = 200;
- res.setHeader('Content-Type', 'text/plain');
- res.end('Hello, World!\n');
- });
- server.listen(port, hostname, () => {
- console.log(`Server running at http://${hostname}:${port}/`);
- });
复制代码
安装PM2:
启动应用:
- cd /var/www/nodeapp
- pm2 start app.js
- pm2 startup
- pm2 save
复制代码
创建Nginx配置文件:
- vim /etc/nginx/conf.d/nodeapp.conf
复制代码
添加以下内容:
- server {
- listen 80;
- server_name nodeapp.example.com;
- location / {
- proxy_pass http://localhost:3000;
- proxy_http_version 1.1;
- proxy_set_header Upgrade $http_upgrade;
- proxy_set_header Connection 'upgrade';
- proxy_set_header Host $host;
- proxy_cache_bypass $http_upgrade;
- }
- access_log /var/log/nginx/nodeapp-access.log;
- error_log /var/log/nginx/nodeapp-error.log;
- }
复制代码
测试并重启Nginx:
- nginx -t
- systemctl restart nginx
复制代码
7. 安全设置和加固
7.1 防火墙配置
检查firewalld状态:
- systemctl status firewalld
复制代码
启动并启用firewalld:
- systemctl start firewalld
- systemctl enable firewalld
复制代码
允许HTTP和HTTPS流量:
- firewall-cmd --permanent --add-service=http
- firewall-cmd --permanent --add-service=https
- firewall-cmd --reload
复制代码
如果需要SSH访问:
- firewall-cmd --permanent --add-service=ssh
- firewall-cmd --reload
复制代码
查看当前规则:
7.2 SSL/TLS配置
使用Let’s Encrypt获取免费SSL证书:
安装Certbot:
- yum install -y certbot python3-certbot-apache
复制代码
获取并安装证书(以Apache为例):
- certbot --apache -d example.com -d www.example.com
复制代码
对于Nginx:
- yum install -y certbot python3-certbot-nginx
- certbot --nginx -d example.com -d www.example.com
复制代码
编辑SSL配置文件:
- vim /etc/httpd/conf.d/ssl.conf
复制代码
确保以下配置正确:
- Listen 443 https
- SSLPassPhraseDialog exec:/usr/libexec/httpd-ssl-pass-dialog
- SSLSessionCache shmcb:/run/httpd/sslcache(512000)
- SSLSessionCacheTimeout 300
- SSLCryptoDevice builtin
- <VirtualHost _default_:443>
- ServerName www.example.com:443
- DocumentRoot "/var/www/html"
- SSLEngine on
- SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
- SSLCipherSuite HIGH:!aNULL:!MD5
- SSLCertificateFile /etc/letsencrypt/live/example.com/cert.pem
- SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
- SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem
- </VirtualHost>
复制代码
编辑虚拟主机配置文件:
- vim /etc/nginx/conf.d/example.com.conf
复制代码
添加以下内容:
- server {
- listen 443 ssl http2;
- server_name example.com www.example.com;
- root /var/www/example.com;
- index index.html;
- ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
- ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
- ssl_protocols TLSv1.2 TLSv1.3;
- ssl_ciphers 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384';
- ssl_prefer_server_ciphers off;
- location / {
- try_files $uri $uri/ =404;
- }
- access_log /var/log/nginx/example.com-ssl-access.log;
- error_log /var/log/nginx/example.com-ssl-error.log;
- }
- # 重定向HTTP到HTTPS
- server {
- listen 80;
- server_name example.com www.example.com;
- return 301 https://$host$request_uri;
- }
复制代码
7.3 安全加固
列出所有启用的服务:
- systemctl list-unit-files | grep enabled
复制代码
禁用不必要的服务(示例):
- systemctl disable telnet.socket
- systemctl disable rsh.socket
复制代码
检查SELinux状态:
如果SELinux处于 enforcing 模式,确保Web服务器有正确的权限:
对于Apache:
- setsebool -P httpd_can_network_connect_db on
- setsebool -P httpd_can_network_connect on
- setsebool -P httpd_execmem on
复制代码
对于Nginx:
- setsebool -P httpd_can_network_connect on
- setsebool -P httpd_can_network_connect_db on
复制代码
设置正确的文件权限:
- # 网站文件目录权限
- chown -R apache:apache /var/www/html # 对于Apache
- chown -R nginx:nginx /var/www/html # 对于Nginx
- chmod -R 755 /var/www/html
复制代码
设置正确的上传目录权限:
- mkdir /var/www/html/uploads
- chown -R apache:apache /var/www/html/uploads # 对于Apache
- chown -R nginx:nginx /var/www/html/uploads # 对于Nginx
- chmod -R 755 /var/www/html/uploads
复制代码
对于Apache,编辑配置文件:
- vim /etc/httpd/conf/httpd.conf
复制代码
添加或修改以下指令:
- ServerTokens Prod
- ServerSignature Off
复制代码
对于Nginx,编辑配置文件:
- vim /etc/nginx/nginx.conf
复制代码
在http块中添加:
安装ModSecurity:
- yum install -y mod_security
复制代码
配置ModSecurity:
- cp /etc/httpd/conf.d/mod_security.conf /etc/httpd/conf.d/mod_security.conf.bak
- vim /etc/httpd/conf.d/mod_security.conf
复制代码
确保以下配置正确:
- SecRuleEngine On
- SecRequestBodyAccess On
- SecResponseBodyAccess On
复制代码
下载并配置OWASP核心规则集:
- cd /etc/httpd/
- wget https://github.com/SpiderLabs/owasp-modsecurity-crs/archive/v3.3.0.tar.gz
- tar -xvzf v3.3.0.tar.gz
- mv owasp-modsecurity-crs-3.3.0 /etc/httpd/modsecurity-crs
- cd /etc/httpd/modsecurity-crs
- cp crs-setup.conf.example crs-setup.conf
复制代码
编辑Apache配置文件以包含规则集:
- vim /etc/httpd/conf.d/mod_security.conf
复制代码
添加以下内容:
- Include /etc/httpd/modsecurity-crs/crs-setup.conf
- Include /etc/httpd/modsecurity-crs/rules/*.conf
复制代码
重启Apache:
安装Fail2Ban:
创建并配置jail.local:
- cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
- vim /etc/fail2ban/jail.local
复制代码
配置SSH和HTTP保护:
- [sshd]
- enabled = true
- port = ssh
- logpath = %(sshd_log)s
- maxretry = 3
- bantime = 3600
- [apache-auth]
- enabled = true
- port = http,https
- logpath = %(apache_error_log)s
- maxretry = 3
- bantime = 3600
- [apache-badbots]
- enabled = true
- port = http,https
- logpath = %(apache_access_log)s
- maxretry = 2
- bantime = 86400
复制代码
启动并启用Fail2Ban:
- systemctl start fail2ban
- systemctl enable fail2ban
复制代码
8. 性能优化
8.1 Web服务器性能优化
编辑Apache配置文件:
- vim /etc/httpd/conf/httpd.conf
复制代码
调整MPM(多处理模块)设置(以event MPM为例):
- <IfModule mpm_event_module>
- StartServers 3
- MinSpareThreads 75
- MaxSpareThreads 250
- ThreadsPerChild 25
- MaxRequestWorkers 400
- MaxConnectionsPerChild 10000
- </IfModule>
复制代码
启用KeepAlive:
- KeepAlive On
- MaxKeepAliveRequests 100
- KeepAliveTimeout 5
复制代码
启用缓存:
- yum install -y mod_cache mod_cache_disk
复制代码
编辑配置文件:
- vim /etc/httpd/conf.d/cache.conf
复制代码
添加以下内容:
- <IfModule mod_cache.c>
- CacheQuickHandler off
- CacheLock on
- CacheLockPath /tmp/mod_cache-lock
- CacheLockMaxAge 5
- <IfModule mod_cache_disk.c>
- CacheRoot /var/cache/httpd/mod_cache_disk
- CacheEnable disk /
- CacheDirLevels 2
- CacheDirLength 1
- </IfModule>
- </IfModule>
复制代码
编辑Nginx主配置文件:
- vim /etc/nginx/nginx.conf
复制代码
优化worker进程和连接:
- worker_processes auto;
- worker_rlimit_nofile 100000;
- events {
- worker_connections 4096;
- multi_accept on;
- use epoll;
- }
复制代码
优化HTTP设置:
- http {
- # 基本设置
- sendfile on;
- tcp_nopush on;
- tcp_nodelay on;
- keepalive_timeout 65;
- types_hash_max_size 2048;
- server_tokens off;
- # 缓存设置
- open_file_cache max=100000 inactive=20s;
- open_file_cache_valid 30s;
- open_file_cache_min_uses 2;
- open_file_cache_errors on;
- # Gzip压缩
- gzip on;
- gzip_disable "msie6";
- gzip_vary on;
- gzip_proxied any;
- gzip_comp_level 6;
- gzip_buffers 16 8k;
- gzip_http_version 1.1;
- gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
- }
复制代码
8.2 PHP性能优化
编辑PHP配置文件:
- vim /etc/php.d/opcache.ini
复制代码
优化OPcache设置:
- opcache.enable=1
- opcache.enable_cli=1
- opcache.memory_consumption=128
- opcache.interned_strings_buffer=8
- opcache.max_accelerated_files=4000
- opcache.revalidate_freq=60
- opcache.fast_shutdown=1
- opcache.enable_file_override=0
- opcache.validate_timestamps=1
复制代码
安装PHP-FPM:
配置PHP-FPM池:
- vim /etc/php-fpm.d/www.conf
复制代码
优化设置:
- [www]
- listen = /var/run/php-fpm/php-fpm.sock;
- listen.allowed_clients = 127.0.0.1
- listen.owner = apache
- listen.group = apache
- listen.mode = 0660
- user = apache
- group = apache
- pm = dynamic
- pm.max_children = 50
- pm.start_servers = 5
- pm.min_spare_servers = 5
- pm.max_spare_servers = 35
- pm.max_requests = 500
- slowlog = /var/log/php-fpm/www-slow.log
- php_admin_value[error_log] = /var/log/php-fpm/www-error.log
- php_admin_flag[log_errors] = on
- php_value[session.save_handler] = files
- php_value[session.save_path] = /var/lib/php/session
复制代码
启动并启用PHP-FPM:
- systemctl start php-fpm
- systemctl enable php-fpm
复制代码
安装mod_proxy_fcgi:
- yum install -y mod_proxy_fcgi
复制代码
编辑Apache配置文件:
- vim /etc/httpd/conf.d/php.conf
复制代码
添加以下内容:
- <FilesMatch \.php$>
- SetHandler "proxy:fcgi://127.0.0.1:9000"
- </FilesMatch>
- <Proxy "fcgi://127.0.0.1:9000" enablereuse=on max=10>
- </Proxy>
复制代码
编辑Nginx虚拟主机配置文件:
- vim /etc/nginx/conf.d/example.com.conf
复制代码
添加PHP处理配置:
- server {
- # ... 其他配置 ...
- location ~ \.php$ {
- try_files $uri =404;
- fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
- fastcgi_index index.php;
- fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
- include fastcgi_params;
- }
- }
复制代码
8.3 数据库性能优化
编辑MySQL/MariaDB配置文件:
添加以下优化设置:
- [mysqld]
- # 基本设置
- innodb_buffer_pool_size = 2G
- innodb_log_file_size = 256M
- innodb_log_buffer_size = 8M
- innodb_flush_log_at_trx_commit = 2
- innodb_flush_method = O_DIRECT
- innodb_file_per_table = 1
- # 查询缓存
- query_cache_type = 1
- query_cache_size = 128M
- query_cache_limit = 2M
- # 连接设置
- max_connections = 200
- thread_cache_size = 8
- thread_concurrency = 8
- # 其他设置
- tmp_table_size = 64M
- max_heap_table_size = 64M
- table_open_cache = 256
- sort_buffer_size = 2M
- read_buffer_size = 1M
- read_rnd_buffer_size = 2M
- join_buffer_size = 2M
复制代码
重启MySQL/MariaDB服务:
- systemctl restart mariadb
复制代码
编辑PostgreSQL配置文件:
- vim /var/lib/pgsql/data/postgresql.conf
复制代码
添加以下优化设置:
- # 连接设置
- max_connections = 100
- shared_buffers = 512MB
- effective_cache_size = 2GB
- work_mem = 8MB
- maintenance_work_mem = 64MB
- # 检查点设置
- checkpoint_segments = 16
- checkpoint_completion_target = 0.9
- checkpoint_timeout = 15min
- # 日志设置
- wal_buffers = 16MB
- default_statistics_target = 100
- # 其他设置
- random_page_cost = 2.0
- effective_io_concurrency = 100
复制代码
重启PostgreSQL服务:
- systemctl restart postgresql
复制代码
8.4 使用缓存系统
安装Redis:
配置Redis:
优化设置:
- maxmemory 256mb
- maxmemory-policy allkeys-lru
- save 900 1
- save 300 10
- save 60 10000
复制代码
启动并启用Redis:
- systemctl start redis
- systemctl enable redis
复制代码
安装Memcached:
配置Memcached:
- vim /etc/sysconfig/memcached
复制代码
优化设置:
- PORT="11211"
- USER="memcached"
- MAXCONN="1024"
- CACHESIZE="256"
- OPTIONS="-l 127.0.0.1"
复制代码
启动并启用Memcached:
- systemctl start memcached
- systemctl enable memcached
复制代码
安装PHP扩展:
- yum install -y php-pecl-redis php-pecl-memcached
复制代码
重启PHP-FPM:
- systemctl restart php-fpm
复制代码
在PHP应用中使用Redis:
- <?php
- $redis = new Redis();
- $redis->connect('127.0.0.1', 6379);
- // 设置缓存
- $redis->set('key', 'value', 3600); // 缓存1小时
- // 获取缓存
- $value = $redis->get('key');
- echo $value;
- ?>
复制代码
在PHP应用中使用Memcached:
- <?php
- $memcached = new Memcached();
- $memcached->addServer('127.0.0.1', 11211);
- // 设置缓存
- $memcached->set('key', 'value', 3600); // 缓存1小时
- // 获取缓存
- $value = $memcached->get('key');
- echo $value;
- ?>
复制代码
9. 高可用性和负载均衡
9.1 使用Keepalived实现高可用性
在两台服务器上安装Keepalived:
- yum install -y keepalived
复制代码
在主服务器上编辑配置文件:
- vim /etc/keepalived/keepalived.conf
复制代码
添加以下内容:
- ! Configuration File for keepalived
- global_defs {
- notification_email {
- admin@example.com
- }
- notification_email_from keepalived@example.com
- smtp_server 127.0.0.1
- smtp_connect_timeout 30
- router_id LVS_MAIN
- }
- vrrp_script chk_httpd {
- script "killall -0 httpd"
- interval 2
- weight 2
- }
- vrrp_instance VI_1 {
- state MASTER
- interface eth0
- virtual_router_id 51
- priority 100
- advert_int 1
- authentication {
- auth_type PASS
- auth_pass 1111
- }
- virtual_ipaddress {
- 192.168.1.100
- }
- track_script {
- chk_httpd
- }
- }
复制代码
在备用服务器上编辑配置文件:
- vim /etc/keepalived/keepalived.conf
复制代码
添加以下内容(注意state和priority的不同):
- ! Configuration File for keepalived
- global_defs {
- notification_email {
- admin@example.com
- }
- notification_email_from keepalived@example.com
- smtp_server 127.0.0.1
- smtp_connect_timeout 30
- router_id LVS_BACKUP
- }
- vrrp_script chk_httpd {
- script "killall -0 httpd"
- interval 2
- weight 2
- }
- vrrp_instance VI_1 {
- state BACKUP
- interface eth0
- virtual_router_id 51
- priority 90
- advert_int 1
- authentication {
- auth_type PASS
- auth_pass 1111
- }
- virtual_ipaddress {
- 192.168.1.100
- }
- track_script {
- chk_httpd
- }
- }
复制代码
在两台服务器上执行:
- systemctl start keepalived
- systemctl enable keepalived
复制代码
检查主服务器上的虚拟IP:
停止主服务器上的Web服务:
检查备用服务器是否接管了虚拟IP:
9.2 使用HAProxy实现负载均衡
编辑HAProxy配置文件:
- vim /etc/haproxy/haproxy.cfg
复制代码
添加以下内容:
- #---------------------------------------------------------------------
- # Global settings
- #---------------------------------------------------------------------
- global
- log 127.0.0.1 local2
- chroot /var/lib/haproxy
- pidfile /var/run/haproxy.pid
- maxconn 4000
- user haproxy
- group haproxy
- daemon
- # turn on stats unix socket
- stats socket /var/lib/haproxy/stats
- #---------------------------------------------------------------------
- # common defaults that all the 'listen' and 'backend' sections will
- # use if not designated in their block
- #---------------------------------------------------------------------
- defaults
- mode http
- log global
- option httplog
- option dontlognull
- option http-server-close
- option forwardfor except 127.0.0.0/8
- option redispatch
- retries 3
- timeout http-request 10s
- timeout queue 1m
- timeout connect 10s
- timeout client 1m
- timeout server 1m
- timeout http-keep-alive 10s
- timeout check 10s
- maxconn 3000
- #---------------------------------------------------------------------
- # main frontend which proxys to the backends
- #---------------------------------------------------------------------
- frontend main *:80
- acl url_static path_beg -i /static /images /javascript /stylesheets
- acl url_static path_end -i .jpg .gif .png .css .js
- use_backend static if url_static
- default_backend app
- #---------------------------------------------------------------------
- # static backend for serving up images, stylesheets and such
- #---------------------------------------------------------------------
- backend static
- balance roundrobin
- server static1 192.168.1.10:80 check
- server static2 192.168.1.11:80 check
- #---------------------------------------------------------------------
- # round robin balancing between the various backends
- #---------------------------------------------------------------------
- backend app
- balance roundrobin
- server app1 192.168.1.10:80 check
- server app2 192.168.1.11:80 check
- server app3 192.168.1.12:80 check
复制代码- systemctl start haproxy
- systemctl enable haproxy
复制代码
编辑HAProxy配置文件,添加以下内容:
- listen stats
- bind *:8404
- stats enable
- stats uri /stats
- stats refresh 30s
- stats auth admin:password
- stats hide-version
复制代码
重启HAProxy:
- systemctl restart haproxy
复制代码
9.3 使用Nginx作为负载均衡器
编辑Nginx配置文件:
- vim /etc/nginx/nginx.conf
复制代码
在http块中添加 upstream 配置:
- http {
- # ... 其他配置 ...
- upstream backend {
- server 192.168.1.10:80 weight=3;
- server 192.168.1.11:80;
- server 192.168.1.12:80 backup;
- }
- server {
- listen 80;
- server_name lb.example.com;
- location / {
- proxy_pass http://backend;
- proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- }
- # 状态页面
- location /nginx_status {
- stub_status on;
- access_log off;
- allow 127.0.0.1;
- deny all;
- }
- }
- }
复制代码- nginx -t
- systemctl restart nginx
复制代码
10. 监控和日志管理
10.1 系统监控
安装Nagios和相关组件:
- yum install -y nagios nagios-plugins-all nrpe
复制代码
配置Nagios:
- vim /etc/nagios/nagios.cfg
复制代码
确保以下配置正确:
- log_file=/var/log/nagios/nagios.log
- cfg_file=/etc/nagios/objects/commands.cfg
- cfg_file=/etc/nagios/objects/contacts.cfg
- cfg_file=/etc/nagios/objects/timeperiods.cfg
- cfg_file=/etc/nagios/objects/templates.cfg
- cfg_file=/etc/nagios/objects/servers.cfg
复制代码
创建服务器配置文件:
- vim /etc/nagios/objects/servers.cfg
复制代码
添加要监控的服务器:
- define host {
- use linux-server
- host_name webserver1
- alias Web Server 1
- address 192.168.1.10
- max_check_attempts 5
- check_period 24x7
- notification_interval 30
- notification_period 24x7
- }
- define service {
- use generic-service
- host_name webserver1
- service_description HTTP
- check_command check_http
- max_check_attempts 3
- normal_check_interval 5
- retry_check_interval 1
- }
复制代码
启动并启用Nagios:
- systemctl start nagios
- systemctl enable nagios
复制代码
安装Zabbix仓库:
- rpm -Uvh https://repo.zabbix.com/zabbix/5.0/rhel/8/x86_64/zabbix-release-5.0-1.el8.noarch.rpm
复制代码
安装Zabbix服务器和前端:
- yum install -y zabbix-server-mysql zabbix-web-mysql zabbix-apache-conf zabbix-agent
复制代码
创建Zabbix数据库和用户:
- create database zabbix character set utf8 collate utf8_bin;
- create user zabbix@localhost identified by 'password';
- grant all privileges on zabbix.* to zabbix@localhost;
- quit;
复制代码
导入初始数据:
- zcat /usr/share/doc/zabbix-server-mysql*/create.sql.gz | mysql -uzabbix -p zabbix
复制代码
配置Zabbix服务器:
- vim /etc/zabbix/zabbix_server.conf
复制代码
设置数据库连接:
- DBHost=localhost
- DBName=zabbix
- DBUser=zabbix
- DBPassword=password
复制代码
配置PHP:
- vim /etc/php-fpm.d/zabbix.conf
复制代码
设置时区:
- php_value[date.timezone] = Asia/Shanghai
复制代码
启动并启用Zabbix服务:
- systemctl restart zabbix-server zabbix-agent httpd php-fpm
- systemctl enable zabbix-server zabbix-agent httpd php-fpm
复制代码
10.2 日志管理
编辑Apache日志轮转配置:
- vim /etc/logrotate.d/httpd
复制代码
确保以下配置正确:
- /var/log/httpd/*log {
- missingok
- notifempty
- sharedscripts
- delaycompress
- postrotate
- /bin/systemctl reload httpd.service > /dev/null 2>/dev/null || true
- endscript
- }
复制代码
编辑Nginx日志轮转配置:
- vim /etc/logrotate.d/nginx
复制代码
确保以下配置正确:
- /var/log/nginx/*.log {
- daily
- missingok
- rotate 52
- compress
- delaycompress
- notifempty
- create 640 nginx adm
- sharedscripts
- postrotate
- if [ -f /var/run/nginx.pid ]; then
- kill -USR1 `cat /var/run/nginx.pid`
- fi
- endscript
- }
复制代码
安装Elasticsearch:
- rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch
- vim /etc/yum.repos.d/elasticsearch.repo
复制代码
添加以下内容:
- [elasticsearch-7.x]
- name=Elasticsearch repository for 7.x packages
- baseurl=https://artifacts.elastic.co/packages/7.x/yum
- gpgcheck=1
- gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
- enabled=1
- autorefresh=1
- type=rpm-md
复制代码
安装Elasticsearch:
- yum install -y elasticsearch
复制代码
配置Elasticsearch:
- vim /etc/elasticsearch/elasticsearch.yml
复制代码
设置以下参数:
- network.host: 0.0.0.0
- discovery.type: single-node
复制代码
启动并启用Elasticsearch:
- systemctl start elasticsearch
- systemctl enable elasticsearch
复制代码
安装Logstash:
创建Logstash配置文件:
- vim /etc/logstash/conf.d/apache.conf
复制代码
添加以下内容:
- input {
- file {
- path => "/var/log/httpd/access_log"
- start_position => "beginning"
- }
- }
- filter {
- grok {
- match => { "message" => "%{COMBINEDAPACHELOG}" }
- }
- date {
- match => [ "timestamp" , "dd/MMM/yyyy:HH:mm:ss Z" ]
- }
- }
- output {
- elasticsearch {
- hosts => ["localhost:9200"]
- index => "apache-access-%{+YYYY.MM.dd}"
- }
- stdout { codec => rubydebug }
- }
复制代码
启动并启用Logstash:
- systemctl start logstash
- systemctl enable logstash
复制代码
安装Kibana:
配置Kibana:
- vim /etc/kibana/kibana.yml
复制代码
设置以下参数:
- server.host: "0.0.0.0"
- elasticsearch.hosts: ["http://localhost:9200"]
复制代码
启动并启用Kibana:
- systemctl start kibana
- systemctl enable kibana
复制代码
11. 故障排除方案
11.1 Web服务器常见问题
检查Apache配置文件语法:
如果配置文件有语法错误,修复错误后再次尝试启动。
检查端口占用情况:
- netstat -tulnp | grep :80
复制代码
如果端口被占用,可以停止占用端口的进程或更改Apache监听的端口。
查看Apache错误日志:
- tail -f /var/log/httpd/error_log
复制代码
检查Nginx配置文件语法:
如果配置文件有语法错误,修复错误后再次尝试启动。
检查端口占用情况:
- netstat -tulnp | grep :80
复制代码
如果端口被占用,可以停止占用端口的进程或更改Nginx监听的端口。
查看Nginx错误日志:
- tail -f /var/log/nginx/error.log
复制代码
检查Web服务器状态:
- systemctl status httpd # 对于Apache
- systemctl status nginx # 对于Nginx
复制代码
检查防火墙设置:
确保HTTP和HTTPS服务已允许通过防火墙。
检查SELinux状态:
如果SELinux处于enforcing模式,确保Web服务器有正确的权限。
检查文件权限:
确保网站文件有正确的权限。
11.2 PHP相关问题
检查PHP是否已安装:
检查PHP-FPM状态:
检查Web服务器与PHP-FPM的连接配置。
对于Apache,检查以下配置:
- <FilesMatch \.php$>
- SetHandler "proxy:fcgi://127.0.0.1:9000"
- </FilesMatch>
复制代码
对于Nginx,检查以下配置:
- location ~ \.php$ {
- try_files $uri =404;
- fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
- fastcgi_index index.php;
- fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
- include fastcgi_params;
- }
复制代码
检查PHP错误日志位置:
- grep error_log /etc/php.ini
复制代码
查看PHP错误日志:
- tail -f /var/log/php/error.log
复制代码
11.3 数据库相关问题
检查MySQL/MariaDB服务状态:
检查MySQL/MariaDB日志:
- tail -f /var/log/mariadb/mariadb.log
复制代码
检查MySQL/MariaDB配置:
检查连接权限:
- SELECT host, user FROM mysql.user;
复制代码
检查PostgreSQL服务状态:
- systemctl status postgresql
复制代码
检查PostgreSQL日志:
- tail -f /var/log/postgresql/postgresql-*.log
复制代码
检查PostgreSQL配置:
- cat /var/lib/pgsql/data/postgresql.conf
- cat /var/lib/pgsql/data/pg_hba.conf
复制代码
11.4 性能问题
检查系统负载:
检查CPU使用情况:
- cat /proc/cpuinfo
- mpstat 1 5
复制代码
检查内存使用情况:
检查磁盘I/O:
检查Apache状态:
检查Nginx状态:
- curl http://localhost/nginx_status
复制代码
检查数据库性能:
- mysqladmin processlist -u root -p
复制代码
检查PHP-FPM状态:
11.5 安全问题
检查系统日志:
- tail -f /var/log/messages
- tail -f /var/log/secure
复制代码
检查Web服务器访问日志:
- tail -f /var/log/httpd/access_log
- tail -f /var/log/nginx/access.log
复制代码
检查异常进程:
检查异常网络连接:
检查计划任务:
- crontab -l
- ls -la /etc/cron.*
复制代码
隔离受影响的系统:
- iptables -A INPUT -s <攻击者IP> -j DROP
复制代码
收集证据:
- mkdir /tmp/forensics
- cp /var/log/* /tmp/forensics/
- ps aux > /tmp/forensics/processes.txt
- netstat -tulnp > /tmp/forensics/connections.txt
复制代码
恢复系统:
- # 从备份恢复网站文件
- # 重置密码
- # 更新系统
- # 重新配置安全设置
复制代码
12. 总结和最佳实践
在本指南中,我们详细介绍了如何在Red Hat Enterprise Linux上部署企业级Web服务器的全过程。从基础系统安装到高级配置,包括安全设置、性能优化和故障排除方案,我们涵盖了Web服务器部署的各个方面。
12.1 最佳实践总结
1. 系统安全保持系统更新:定期应用安全补丁和更新使用防火墙:仅开放必要的端口和服务启用SELinux:适当配置SELinux以增强系统安全性最小权限原则:为服务和用户分配最小必要权限
2. 保持系统更新:定期应用安全补丁和更新
3. 使用防火墙:仅开放必要的端口和服务
4. 启用SELinux:适当配置SELinux以增强系统安全性
5. 最小权限原则:为服务和用户分配最小必要权限
6. Web服务器配置选择合适的Web服务器:根据应用需求选择Apache或Nginx虚拟主机配置:为每个网站创建独立的虚拟主机配置SSL/TLS配置:为所有网站启用HTTPS隐藏服务器信息:减少攻击面
7. 选择合适的Web服务器:根据应用需求选择Apache或Nginx
8. 虚拟主机配置:为每个网站创建独立的虚拟主机配置
9. SSL/TLS配置:为所有网站启用HTTPS
10. 隐藏服务器信息:减少攻击面
11. 性能优化资源监控:定期监控系统资源使用情况缓存策略:实施适当的缓存策略以提高性能负载均衡:在高流量环境中使用负载均衡数据库优化:优化数据库配置和查询
12. 资源监控:定期监控系统资源使用情况
13. 缓存策略:实施适当的缓存策略以提高性能
14. 负载均衡:在高流量环境中使用负载均衡
15. 数据库优化:优化数据库配置和查询
16. 高可用性冗余设计:避免单点故障故障转移:实施自动故障转移机制备份策略:定期备份重要数据和配置灾难恢复计划:制定并测试灾难恢复计划
17. 冗余设计:避免单点故障
18. 故障转移:实施自动故障转移机制
19. 备份策略:定期备份重要数据和配置
20. 灾难恢复计划:制定并测试灾难恢复计划
21. 日志和监控集中日志管理:使用ELK Stack等工具集中管理日志系统监控:实施全面的系统监控告警机制:设置适当的告警阈值和通知机制定期审查:定期审查日志和监控数据
22. 集中日志管理:使用ELK Stack等工具集中管理日志
23. 系统监控:实施全面的系统监控
24. 告警机制:设置适当的告警阈值和通知机制
25. 定期审查:定期审查日志和监控数据
系统安全
• 保持系统更新:定期应用安全补丁和更新
• 使用防火墙:仅开放必要的端口和服务
• 启用SELinux:适当配置SELinux以增强系统安全性
• 最小权限原则:为服务和用户分配最小必要权限
Web服务器配置
• 选择合适的Web服务器:根据应用需求选择Apache或Nginx
• 虚拟主机配置:为每个网站创建独立的虚拟主机配置
• SSL/TLS配置:为所有网站启用HTTPS
• 隐藏服务器信息:减少攻击面
性能优化
• 资源监控:定期监控系统资源使用情况
• 缓存策略:实施适当的缓存策略以提高性能
• 负载均衡:在高流量环境中使用负载均衡
• 数据库优化:优化数据库配置和查询
高可用性
• 冗余设计:避免单点故障
• 故障转移:实施自动故障转移机制
• 备份策略:定期备份重要数据和配置
• 灾难恢复计划:制定并测试灾难恢复计划
日志和监控
• 集中日志管理:使用ELK Stack等工具集中管理日志
• 系统监控:实施全面的系统监控
• 告警机制:设置适当的告警阈值和通知机制
• 定期审查:定期审查日志和监控数据
12.2 持续改进
Web服务器部署不是一次性的任务,而是一个持续改进的过程。以下是一些建议:
1. 定期评估定期评估系统性能和安全性根据业务需求调整配置跟踪新技术和最佳实践
2. 定期评估系统性能和安全性
3. 根据业务需求调整配置
4. 跟踪新技术和最佳实践
5. 文档化维护详细的系统文档记录配置更改和原因创建操作手册和故障排除指南
6. 维护详细的系统文档
7. 记录配置更改和原因
8. 创建操作手册和故障排除指南
9. 培训和学习保持对最新安全威胁的了解参加相关培训和认证加入专业社区和论坛
10. 保持对最新安全威胁的了解
11. 参加相关培训和认证
12. 加入专业社区和论坛
定期评估
• 定期评估系统性能和安全性
• 根据业务需求调整配置
• 跟踪新技术和最佳实践
文档化
• 维护详细的系统文档
• 记录配置更改和原因
• 创建操作手册和故障排除指南
培训和学习
• 保持对最新安全威胁的了解
• 参加相关培训和认证
• 加入专业社区和论坛
通过遵循本指南中提供的步骤和最佳实践,您将能够在Red Hat Enterprise Linux上成功部署和管理安全、高性能的企业级Web服务器。记住,每个环境都是独特的,可能需要根据特定需求进行调整。始终保持警惕,定期审查和更新您的配置,以确保您的Web服务器始终保持最佳状态。 |
|