网站服务器配置完全指南

AI 生成

网站服务器配置完全指南

本文详细介绍如何配置高性能、安全的Web服务器,包括Nginx和Apache的安装配置、SSL证书设置、PHP和缓存优化等内容。

1. Nginx服务器配置

Nginx因其高性能、低内存占用和出色的并发处理能力,成为当前最流行的Web服务器之一。

1.1 安装Nginx

1
2
3
4
5
6
7
# Ubuntu/Debian
apt update
apt install nginx

# CentOS/RHEL
yum install epel-release
yum install nginx

或使用官方源安装最新版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Ubuntu/Debian
echo "deb http://nginx.org/packages/ubuntu/ $(lsb_release -cs) nginx" > /etc/apt/sources.list.d/nginx.list
curl -fsSL https://nginx.org/keys/nginx_signing.key | apt-key add -
apt update
apt install nginx

# CentOS/RHEL
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配置
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压缩
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";
}

# PHP处理
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
# Ubuntu/Debian
apt install certbot python3-certbot-nginx

# CentOS/RHEL
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优化
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;

# ... 其余配置与HTTP相同
}

# HTTP重定向到HTTPS
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; # 自动设为CPU核心数
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压缩优化
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
# Ubuntu/Debian
apt update
apt install apache2

# CentOS/RHEL
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@localhost
ServerName server.example.com

# 模块加载
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule ssl_module modules/mod_ssl.so
# ... 其他模块

# 主要配置
DocumentRoot "/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/*.conf
Include 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
# Ubuntu/Debian: /etc/apache2/sites-available/example.com.conf
# CentOS/RHEL: /etc/httpd/conf.d/example.com.conf

<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>

# PHP配置 (如果使用mod_php)
<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
# Ubuntu/Debian
apt install ssl-cert
a2enmod ssl

# CentOS/RHEL
yum install mod_ssl

使用Certbot获取证书:

1
2
3
4
5
6
7
# Ubuntu/Debian
apt install certbot python3-certbot-apache
certbot --apache -d example.com -d www.example.com

# CentOS/RHEL
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

# SSL优化
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

# HSTS (HTTP Strict Transport Security)
Header always set Strict-Transport-Security "max-age=63072000"

# ... 其余配置与HTTP相同
</VirtualHost>

# HTTP重定向到HTTPS
<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
# MPM Worker 配置 (在/etc/apache2/mods-available/mpm_worker.conf)
<IfModule mpm_worker_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>

# 或使用 MPM Event (更高性能)
<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
# Ubuntu/Debian
apt install php-fpm php-mysql php-common php-gd php-xml php-mbstring php-zip

# CentOS/RHEL
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
; php.ini 配置优化

; 内存限制
memory_limit = 256M

; 最大执行时间
max_execution_time = 60
max_input_time = 60

; 文件上传
upload_max_filesize = 20M
post_max_size = 21M

; 错误处理 (生产环境)
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off
display_startup_errors = Off
log_errors = On
error_log = /var/log/php/error.log

; OPcache设置
opcache.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
; PHP-FPM进程管理
pm = dynamic
pm.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
# Ubuntu/Debian
a2enmod proxy_fcgi setenvif
a2enconf php7.4-fpm # 版本可能不同

# CentOS/RHEL
# 模块通常自动加载

配置虚拟主机:

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:

1
server_tokens off;

Apache:

1
2
ServerTokens Prod
ServerSignature 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
# 安装ModSecurity
apt install libapache2-mod-security2 # Ubuntu/Debian
yum install mod_security # CentOS/RHEL

# 配置基本规则
cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf

修改/etc/modsecurity/modsecurity.conf

1
SecRuleEngine On

Nginx:

1
2
3
# 编译安装ModSecurity-nginx
apt install libmodsecurity-dev # Ubuntu/Debian
yum install modsecurity # CentOS/RHEL

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
# 启用http2模块
a2enmod http2 # Ubuntu/Debian

# 配置
<VirtualHost *:443>
Protocols h2 http/1.1
# ... 其他配置
</VirtualHost>

5.3 使用CDN加速

以Cloudflare为例,配置DNS指向Cloudflare,然后:

  1. 在Cloudflare中启用”Proxied”模式
  2. 启用SSL (推荐”Full”或”Full (Strict)”)
  3. 启用缓存和优化功能

5.4 图片优化

安装和使用图片优化工具:

1
2
3
4
5
6
7
# 安装优化工具
apt install jpegoptim optipng # Ubuntu/Debian
yum install jpegoptim optipng # CentOS/RHEL

# 批量优化图片
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
# 安装Redis
apt install redis-server # Ubuntu/Debian
yum install redis # CentOS/RHEL

# 安装PHP Redis扩展
apt install php-redis # Ubuntu/Debian
yum install php-redis # CentOS/RHEL

对于WordPress等CMS,可以安装Redis缓存插件。

6. 监控与维护

6.1 设置日志轮转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 配置logrotate
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
# 创建备份脚本 /usr/local/bin/backup-web-config.sh
#!/bin/bash
BACKUP_DIR="/var/backups/web-config"
DATE=$(date +%Y-%m-%d)
mkdir -p $BACKUP_DIR

# 备份Nginx配置
if [ -d /etc/nginx ]; then
tar -czf $BACKUP_DIR/nginx-$DATE.tar.gz /etc/nginx
fi

# 备份Apache配置
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

# 备份PHP配置
if [ -d /etc/php ]; then
tar -czf $BACKUP_DIR/php-$DATE.tar.gz /etc/php
fi

# 删除超过30天的备份
find $BACKUP_DIR -name "*.tar.gz" -type f -mtime +30 -delete

执行权限与定时任务:

1
2
chmod +x /usr/local/bin/backup-web-config.sh
echo "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
# /usr/local/bin/check-web-services.sh

# 检查服务状态
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 # 或 apache2/httpd
check_service php7.4-fpm # 版本可能不同

# 检查网站
check_website https://example.com

设置定时任务:

1
2
chmod +x /usr/local/bin/check-web-services.sh
echo "*/5 * * * * root /usr/local/bin/check-web-services.sh" > /etc/cron.d/check-web-services

7. 常见问题排查

7.1 504 Gateway Timeout

常见原因:PHP处理超时

解决方案:

  1. 增加Nginx超时设置

    1
    fastcgi_read_timeout 300;
  2. 增加PHP-FPM超时设置

    1
    request_terminate_timeout = 300
  3. 检查PHP脚本性能问题

7.2 403 Forbidden

常见原因:权限问题

解决方案:

  1. 检查文件权限

    1
    2
    3
    chmod -R 755 /var/www/html
    chown -R www-data:www-data /var/www/html # Ubuntu/Debian
    chown -R apache:apache /var/www/html # CentOS/RHEL
  2. 检查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未运行或配置错误

解决方案:

  1. 检查PHP-FPM状态

    1
    systemctl status php7.4-fpm  # 版本可能不同
  2. 检查socket路径是否匹配

    1
    2
    3
    4
    5
    # 查看实际socket路径
    grep "listen =" /etc/php/7.4/fpm/pool.d/www.conf

    # 确保Nginx配置中使用相同路径
    fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;

7.4 性能问题

常见解决方案:

  1. 启用慢日志分析

    1
    2
    3
    ; PHP慢日志
    slowlog = /var/log/php-fpm/slow.log
    request_slowlog_timeout = 5s
  2. 使用性能分析工具

    1
    2
    apt install php-xdebug  # Ubuntu/Debian
    yum install php-pecl-xdebug # CentOS/RHEL
  3. 分析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,通过合理配置和优化,都可以构建出性能优异、安全可靠的网站服务器,为用户提供出色的访问体验。

定期的监控和维护也是确保服务器长期稳定运行的关键,建议制定完善的备份和监控策略。