为WordPress/PHP网站配置Nginx安全防护需要从多个层面进行加固。以下是一套全面的安全配置方案:
server_tokens off;
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https:; img-src 'self' https: data:; style-src 'self' 'unsafe-inline' https:; font-src 'self' https: data:";
location ~* /(wp-config\.php|wp-config-sample\.php|readme\.html|license\.txt|wp-includes/|wp-admin/|xmlrpc\.php) {
deny all;
return 403;
}
location ~* ^/(uploads|files)/.*\.php$ {
deny all;
return 403;
}
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
# 安全相关参数
fastcgi_param PHP_VALUE "open_basedir=$document_root:/tmp/:/var/www/wp-content/uploads/";
fastcgi_param PHP_VALUE "disable_functions=exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source";
fastcgi_param PHP_VALUE "expose_php=Off";
fastcgi_param PHP_VALUE "allow_url_fopen=Off";
fastcgi_param PHP_VALUE "allow_url_include=Off";
}
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
ssl_ecdh_curve secp384r1;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
# 登录页面限速
location = /wp-login.php {
limit_req zone=login burst=3 nodelay;
limit_req_status 444;
try_files $uri =404;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
# 定义限速区域
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
client_max_body_size 20M;
client_body_buffer_size 128k;
access_log /var/log/nginx/wordpress-access.log;
error_log /var/log/nginx/wordpress-error.log;
# 记录可疑请求
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" "$http_x_forwarded_for"';
以上配置应根据实际环境进行调整,并在应用前进行充分测试。安全是一个持续的过程,需要定期审查和更新防护措施。