AI 生成
网站服务器配置完全指南 本文详细介绍如何配置高性能、安全的Web服务器,包括Nginx和Apache的安装配置、SSL证书设置、PHP和缓存优化等内容。
1. Nginx服务器配置 Nginx因其高性能、低内存占用和出色的并发处理能力,成为当前最流行的Web服务器之一。
1.1 安装Nginx 1 2 3 4 5 6 7 apt update apt install nginx yum install epel-release yum install nginx
或使用官方源安装最新版本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 echo "deb http://nginx.org/packages/ubuntu/ $(lsb_release -cs) nginx" > /etc/apt/sources.list.d/nginx.listcurl -fsSL https://nginx.org/keys/nginx_signing.key | apt-key add - apt update apt install nginx cat > /etc/yum.repos.d/nginx.repo << EOF [nginx] name=nginx repo baseurl=https://nginx.org/packages/centos/\$releasever/\$basearch/ gpgcheck=1 enabled=1 gpgkey=https://nginx.org/keys/nginx_signing.key EOF yum install nginx
1.2 基本配置结构 Nginx的配置文件通常位于/etc/nginx/nginx.conf
,主要包含以下部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 user www-data;worker_processes auto;pid /run/nginx.pid;error_log /var/log/nginx/error .log;events { worker_connections 1024 ; multi_accept on ; use epoll ; } http { include mime.types; default_type application/octet-stream; server_tokens off ; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error .log; sendfile on ; tcp_nopush on ; tcp_nodelay on ; keepalive_timeout 65 ; types_hash_max_size 2048 ; gzip on ; gzip_vary on ; gzip_proxied any; gzip_comp_level 6 ; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; include /etc/nginx/conf.d/*.conf ; include /etc/nginx/sites-enabled/*; }
1.3 配置虚拟主机 创建站点配置文件,例如/etc/nginx/sites-available/example.com
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 server { listen 80 ; server_name example.com www.example.com; root /var/www/example.com; index index.html index.htm index.php; error_page 404 /404 .html; error_page 500 502 503 504 /50x.html; location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 30d ; add_header Cache-Control "public, no-transform" ; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root $fastcgi_script_name ; include fastcgi_params; } location ~ /\. { deny all; access_log off ; log_not_found off ; } }
启用站点:
1 2 3 ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/nginx -t systemctl reload nginx
1.4 配置SSL/TLS 安装Certbot获取免费SSL证书:
1 2 3 4 5 apt install certbot python3-certbot-nginx yum install certbot python3-certbot-nginx
获取并安装证书:
1 certbot --nginx -d example.com -d www.example.com
或手动配置SSL:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 server { listen 443 ssl http2; server_name example.com www.example.com; root /var/www/example.com; index index.html index.htm index.php; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem; ssl_protocols TLSv1.2 TLSv1.3 ; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384; ssl_prefer_server_ciphers off ; ssl_session_cache shared:SSL:10m ; ssl_session_timeout 1d ; ssl_session_tickets off ; ssl_stapling on ; ssl_stapling_verify on ; resolver 8.8.8.8 8.8.4.4 valid=300s ; resolver_timeout 5s ; add_header Strict-Transport-Security "max-age=63072000" always; } server { listen 80 ; server_name example.com www.example.com; return 301 https://$host $request_uri ; }
1.5 优化Nginx性能 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 worker_processes auto; worker_rlimit_nofile 65535 ; events { worker_connections 10240 ; multi_accept on ; use epoll ; } http { open_file_cache max=200000 inactive=20s ; open_file_cache_valid 30s ; open_file_cache_min_uses 2 ; open_file_cache_errors on ; client_body_buffer_size 10K ; client_header_buffer_size 1k ; client_max_body_size 8m ; large_client_header_buffers 2 1k ; client_body_timeout 12 ; client_header_timeout 12 ; keepalive_timeout 15 ; send_timeout 10 ; gzip on ; gzip_comp_level 5 ; gzip_min_length 256 ; gzip_proxied any; gzip_vary on ; gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy; }
2. Apache服务器配置 Apache HTTP Server是历史最悠久的Web服务器之一,具有强大的功能和模块化设计。
2.1 安装Apache 1 2 3 4 5 6 apt update apt install apache2 yum install httpd
2.2 基本配置结构 Apache的主配置文件通常位于:
Ubuntu/Debian: /etc/apache2/apache2.conf
CentOS/RHEL: /etc/httpd/conf/httpd.conf
基本配置结构:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ServerRoot "/etc/apache2" Listen 80 ServerAdmin webmaster@localhostServerName server.example.comLoadModule rewrite_module modules/mod_rewrite.soLoadModule ssl_module modules/mod_ssl.soDocumentRoot "/var/www/html" <Directory "/var/www/html" > Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> <VirtualHost *:80 > ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR} /error.log CustomLog ${APACHE_LOG_DIR} /access.log combined </VirtualHost> Include conf.d/*.confInclude sites-enabled/*.conf
2.3 配置虚拟主机 创建虚拟主机配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <VirtualHost *:80 > ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com ErrorLog ${APACHE_LOG_DIR} /example.com_error.log CustomLog ${APACHE_LOG_DIR} /example.com_access.log combined <Directory /var/www/example.com> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> <FilesMatch \.php$> SetHandler application/x-httpd-php </FilesMatch> </VirtualHost>
在Ubuntu/Debian上启用站点:
1 2 a2ensite example.com.conf systemctl reload apache2
2.4 配置SSL/TLS 安装SSL模块:
1 2 3 4 5 6 apt install ssl-cert a2enmod ssl yum install mod_ssl
使用Certbot获取证书:
1 2 3 4 5 6 7 apt install certbot python3-certbot-apache certbot --apache -d example.com -d www.example.com yum install certbot python3-certbot-apache certbot --apache -d example.com -d www.example.com
或手动配置SSL:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <VirtualHost *:443 > ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com SSLEngine on SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1 SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384 SSLHonorCipherOrder off SSLSessionTickets off SSLSessionCache shmcb:/var/lib/apache2/ssl_scache(512000 ) SSLSessionTimeout 300 Header always set Strict-Transport-Security "max-age=63072000" </VirtualHost> <VirtualHost *:80 > ServerName example.com ServerAlias www.example.com Redirect permanent / https://example.com/ </VirtualHost>
2.5 优化Apache性能 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 <IfModule mpm_worker_module> StartServers 2 MinSpareThreads 25 MaxSpareThreads 75 ThreadLimit 64 ThreadsPerChild 25 MaxRequestWorkers 150 MaxConnectionsPerChild 0 </IfModule> <IfModule mpm_event_module> StartServers 2 MinSpareThreads 25 MaxSpareThreads 75 ThreadLimit 64 ThreadsPerChild 25 MaxRequestWorkers 150 MaxConnectionsPerChild 0 </IfModule> <IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType text/css "access plus 1 month" ExpiresByType application/javascript "access plus 1 month" ExpiresByType text/javascript "access plus 1 month" ExpiresByType application/x-javascript "access plus 1 month" ExpiresByType text/html "access plus 1 month" ExpiresByType application/xhtml+xml "access plus 1 month" </IfModule> <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css AddOutputFilterByType DEFLATE application/x-javascript application/javascript application/ecmascript AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/xml </IfModule>
在Ubuntu/Debian上,切换MPM模块:
1 2 3 a2dismod mpm_prefork a2enmod mpm_event systemctl restart apache2
3. PHP配置优化 无论使用Nginx还是Apache,正确配置PHP对网站性能都至关重要。
3.1 安装PHP-FPM 1 2 3 4 5 apt install php-fpm php-mysql php-common php-gd php-xml php-mbstring php-zip yum install php-fpm php-mysqlnd php-common php-gd php-xml php-mbstring php-zip
3.2 配置PHP-FPM 主配置文件位于:
Ubuntu/Debian: /etc/php/7.4/fpm/php.ini
(版本号可能不同)
CentOS/RHEL: /etc/php.ini
和 /etc/php-fpm.d/www.conf
性能优化:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 memory_limit = 256 Mmax_execution_time = 60 max_input_time = 60 upload_max_filesize = 20 Mpost_max_size = 21 Merror_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICTdisplay_errors = Off display_startup_errors = Off log_errors = On error_log = /var/log/php/error.logopcache.enable =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_cli =1
PHP-FPM池配置 (www.conf
):
1 2 3 4 5 6 7 8 9 10 pm = dynamicpm.max_children = 50 pm.start_servers = 5 pm.min_spare_servers = 5 pm.max_spare_servers = 35 pm.max_requests = 500 request_terminate_timeout = 300
3.3 与Nginx集成 1 2 3 4 5 6 7 8 9 10 11 location ~ \.php$ { fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root $fastcgi_script_name ; include fastcgi_params; fastcgi_buffer_size 128k ; fastcgi_buffers 256 16k ; fastcgi_busy_buffers_size 256k ; fastcgi_temp_file_write_size 256k ; fastcgi_read_timeout 300 ; }
3.4 与Apache集成 首先启用必要的模块:
1 2 3 4 5 6 a2enmod proxy_fcgi setenvif a2enconf php7.4-fpm
配置虚拟主机:
1 2 3 4 5 6 7 <VirtualHost *:80 > <FilesMatch \.php$> SetHandler "proxy:unix:/var/run/php/php7.4-fpm.sock|fcgi://localhost" </FilesMatch> </VirtualHost>
4. Web服务器安全加固 4.1 隐藏服务器信息 Nginx:
Apache:
1 2 ServerTokens ProdServerSignature Off
4.2 防XSS和点击劫持 添加安全响应头:
Nginx:
1 2 3 4 5 add_header X-XSS-Protection "1; mode=block" always;add_header X-Content-Type-Options "nosniff" always;add_header X-Frame-Options "SAMEORIGIN" always;add_header Content-Security-Policy "default-src 'self' https: data: 'unsafe-inline' 'unsafe-eval';" always;add_header Referrer-Policy "no-referrer-when-downgrade" always;
Apache:
1 2 3 4 5 6 7 <IfModule mod_headers.c> Header set X-XSS-Protection "1; mode=block" Header set X-Content-Type-Options "nosniff" Header set X-Frame-Options "SAMEORIGIN" Header set Content-Security-Policy "default-src 'self' https: data: 'unsafe-inline' 'unsafe-eval';" Header set Referrer-Policy "no-referrer-when-downgrade" </IfModule>
4.3 限制不必要的HTTP方法 Nginx:
1 2 3 if ($request_method !~ ^(GET|HEAD|POST)$) { return 405 ; }
Apache:
1 2 3 <LimitExcept GET POST HEAD> deny from all </LimitExcept>
4.4 防止目录遍历 Nginx:
1 2 3 location ~ /\.(?!well-known) { deny all; }
Apache:
1 2 3 4 <Directory /var/www/html> Options -Indexes AllowOverride None </Directory>
4.5 使用ModSecurity Web应用防火墙 Apache:
1 2 3 4 5 6 apt install libapache2-mod-security2 yum install mod_security cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
修改/etc/modsecurity/modsecurity.conf
:
Nginx:
1 2 3 apt install libmodsecurity-dev yum install modsecurity
Nginx配置:
1 2 3 4 5 6 7 load_module modules/ngx_http_modsecurity_module.so;server { modsecurity on ; modsecurity_rules_file /etc/nginx/modsec/main.conf; }
5. 网站性能优化 5.1 配置浏览器缓存 Nginx:
1 2 3 4 location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 30d ; add_header Cache-Control "public, no-transform" ; }
Apache:
1 2 3 4 5 6 7 8 9 <IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType text/css "access plus 1 month" ExpiresByType application/javascript "access plus 1 month" </IfModule>
5.2 启用HTTP/2 Nginx:
1 2 3 4 server { listen 443 ssl http2; }
Apache:
1 2 3 4 5 6 7 8 a2enmod http2 <VirtualHost *:443> Protocols h2 http/1.1 </VirtualHost>
5.3 使用CDN加速 以Cloudflare为例,配置DNS指向Cloudflare,然后:
在Cloudflare中启用”Proxied”模式
启用SSL (推荐”Full”或”Full (Strict)”)
启用缓存和优化功能
5.4 图片优化 安装和使用图片优化工具:
1 2 3 4 5 6 7 apt install jpegoptim optipng yum install jpegoptim optipng find /var/www/html -name "*.jpg" -exec jpegoptim --strip-all {} \; find /var/www/html -name "*.png" -exec optipng -o5 {} \;
5.5 使用Redis缓存 1 2 3 4 5 6 7 apt install redis-server yum install redis apt install php-redis yum install php-redis
对于WordPress等CMS,可以安装Redis缓存插件。
6. 监控与维护 6.1 设置日志轮转 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 cat > /etc/logrotate.d/nginx << EOF /var/log/nginx/*.log { daily missingok rotate 14 compress delaycompress notifempty create 0640 www-data adm sharedscripts postrotate if [ -f /var/run/nginx.pid ]; then kill -USR1 \`cat /var/run/nginx.pid\` fi endscript } EOF
6.2 自动备份配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 BACKUP_DIR="/var/backups/web-config" DATE=$(date +%Y-%m-%d) mkdir -p $BACKUP_DIR if [ -d /etc/nginx ]; then tar -czf $BACKUP_DIR /nginx-$DATE .tar.gz /etc/nginx fi if [ -d /etc/apache2 ] || [ -d /etc/httpd ]; then if [ -d /etc/apache2 ]; then tar -czf $BACKUP_DIR /apache-$DATE .tar.gz /etc/apache2 else tar -czf $BACKUP_DIR /apache-$DATE .tar.gz /etc/httpd fi fi if [ -d /etc/php ]; then tar -czf $BACKUP_DIR /php-$DATE .tar.gz /etc/php fi find $BACKUP_DIR -name "*.tar.gz" -type f -mtime +30 -delete
执行权限与定时任务:
1 2 chmod +x /usr/local/bin/backup-web-config.shecho "0 2 * * * root /usr/local/bin/backup-web-config.sh" > /etc/cron.d/backup-web-config
6.3 监控服务状态 使用简单监控脚本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 #!/bin/bash check_service () { systemctl is-active --quiet $1 if [ $? -eq 0 ]; then echo "$1 is running" else echo "$1 is DOWN!" systemctl restart $1 echo "$1 was down on $(hostname) and has been restarted" | mail -s "Service Alert: $1 " admin@example.com fi } check_website () { HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" $1 ) if [ "$HTTP_CODE " = "200" ] || [ "$HTTP_CODE " = "301" ] || [ "$HTTP_CODE " = "302" ]; then echo "$1 is accessible (HTTP $HTTP_CODE )" else echo "$1 is DOWN! (HTTP $HTTP_CODE )" echo "$1 is returning HTTP $HTTP_CODE on $(hostname) " | mail -s "Website Alert: $1 " admin@example.com fi } check_service nginx check_service php7.4-fpm check_website https://example.com
设置定时任务:
1 2 chmod +x /usr/local/bin/check-web-services.shecho "*/5 * * * * root /usr/local/bin/check-web-services.sh" > /etc/cron.d/check-web-services
7. 常见问题排查 7.1 504 Gateway Timeout 常见原因:PHP处理超时
解决方案:
增加Nginx超时设置
1 fastcgi_read_timeout 300 ;
增加PHP-FPM超时设置
1 request_terminate_timeout = 300
检查PHP脚本性能问题
7.2 403 Forbidden 常见原因:权限问题
解决方案:
检查文件权限
1 2 3 chmod -R 755 /var/www/htmlchown -R www-data:www-data /var/www/html chown -R apache:apache /var/www/html
检查SELinux (CentOS/RHEL)
1 2 3 4 restorecon -R /var/www/html semanage fcontext -a -t httpd_sys_content_t "/var/www/html(/.*)?" restorecon -R /var/www/html
7.3 502 Bad Gateway 常见原因:PHP-FPM未运行或配置错误
解决方案:
检查PHP-FPM状态
1 systemctl status php7.4-fpm
检查socket路径是否匹配
1 2 3 4 5 grep "listen =" /etc/php/7.4/fpm/pool.d/www.conf fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
7.4 性能问题 常见解决方案:
启用慢日志分析
1 2 3 slowlog = /var/log/php-fpm/slow.logrequest_slowlog_timeout = 5 s
使用性能分析工具
1 2 apt install php-xdebug yum install php-pecl-xdebug
分析MySQL查询
1 2 3 4 slow_query_log = 1 slow_query_log_file = /var/log/mysql/slow.log long_query_time = 1
总结 配置高性能、安全的Web服务器需要综合考虑多方面因素,包括Web服务器本身的配置、PHP解释器的优化、SSL证书的设置、安全加固措施以及性能优化。
无论选择Nginx还是Apache,通过合理配置和优化,都可以构建出性能优异、安全可靠的网站服务器,为用户提供出色的访问体验。
定期的监控和维护也是确保服务器长期稳定运行的关键,建议制定完善的备份和监控策略。