尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

Nginx Web服务器配置与性能优化指南

Nginx Web服务器配置与性能优化指南 1. Nginx Web服务器基础配置指南Nginx作为当前最流行的开源Web服务器之一凭借其高性能、低资源消耗和模块化设计已经成为各类网站和应用的首选服务端解决方案。我在实际运维工作中发现即使是基础的Nginx配置也有许多值得注意的细节和技巧。本文将分享从安装到核心配置的完整流程特别适合刚接触Nginx的开发者或运维人员参考。2. Nginx安装与环境准备2.1 系统环境检查与依赖安装在开始安装前建议先更新系统并安装基础依赖# Ubuntu/Debian系统 sudo apt update sudo apt upgrade -y sudo apt install build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev -y # CentOS/RHEL系统 sudo yum update -y sudo yum install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel -y注意生产环境建议使用稳定版操作系统避免使用过于前沿的发行版以减少兼容性问题。2.2 源码编译安装Nginx虽然各Linux发行版提供软件包安装方式但源码编译可以获取最新版本并自定义模块wget http://nginx.org/download/nginx-1.25.3.tar.gz tar zxvf nginx-1.25.3.tar.gz cd nginx-1.25.3 # 基础编译配置 ./configure --prefix/usr/local/nginx \ --with-http_ssl_module \ --with-http_realip_module \ --with-http_stub_status_module make sudo make install关键编译参数说明--with-http_ssl_module启用HTTPS支持--with-http_realip_module获取客户端真实IP--with-http_stub_status_module启用状态监控页面2.3 系统服务配置为了方便管理建议创建systemd服务文件sudo tee /etc/systemd/system/nginx.service EOF [Unit] DescriptionThe NGINX HTTP and reverse proxy server Aftersyslog.target network.target remote-fs.target nss-lookup.target [Service] Typeforking PIDFile/usr/local/nginx/logs/nginx.pid ExecStartPre/usr/local/nginx/sbin/nginx -t ExecStart/usr/local/nginx/sbin/nginx ExecReload/usr/local/nginx/sbin/nginx -s reload ExecStop/bin/kill -s QUIT $MAINPID PrivateTmptrue [Install] WantedBymulti-user.target EOF # 启用服务 sudo systemctl enable nginx sudo systemctl start nginx3. 核心配置文件解析3.1 配置文件结构说明Nginx主配置文件通常位于/usr/local/nginx/conf/nginx.conf主要包含以下结构块main # 全局配置 events { # 事件模块配置 ... } http { # HTTP服务配置 ... server { # 虚拟主机配置 ... location / { # URL路径配置 ... } } }3.2 基础Web服务器配置示例一个完整的静态网站配置示例worker_processes auto; # 自动匹配CPU核心数 events { worker_connections 1024; # 每个worker进程最大连接数 use epoll; # Linux系统建议使用epoll模型 } http { include mime.types; default_type application/octet-stream; sendfile on; tcp_nopush on; keepalive_timeout 65; # 日志格式定义 log_format main $remote_addr - $remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for; server { listen 80; server_name example.com www.example.com; access_log logs/example.access.log main; error_log logs/example.error.log; location / { root /var/www/example.com; index index.html index.htm; } # 禁止访问隐藏文件 location ~ /\. { deny all; } } }3.3 关键配置参数详解性能相关参数worker_processes建议设置为CPU核心数worker_connections单个进程最大连接数需结合系统ulimit -n值调整keepalive_timeout长连接保持时间建议60-75秒日志配置技巧生产环境建议将访问日志和错误日志分开可针对不同虚拟主机配置独立日志文件定期日志切割可通过logrotate实现安全加固建议禁用server tokensserver_tokens off;限制HTTP方法limit_except GET POST { deny all; }设置安全头部add_header X-Frame-Options SAMEORIGIN; add_header X-Content-Type-Options nosniff; add_header X-XSS-Protection 1; modeblock;4. 高级配置实战4.1 HTTPS安全配置使用Lets Encrypt免费证书配置HTTPSserver { listen 443 ssl http2; server_name example.com; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # SSL协议配置 ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; ssl_ciphers EECDHAESGCM:EDHAESGCM:AES256EECDH:AES256EDH; ssl_ecdh_curve secp384r1; ssl_session_cache shared:SSL:10m; ssl_session_tickets off; ssl_stapling on; ssl_stapling_verify on; # HSTS策略 add_header Strict-Transport-Security max-age63072000; includeSubDomains; preload; location / { root /var/www/example.com; index index.html index.htm; } } # HTTP强制跳转HTTPS server { listen 80; server_name example.com; return 301 https://$host$request_uri; }4.2 反向代理配置将请求代理到后端应用服务器upstream backend { server 127.0.0.1:8000; server 127.0.0.1:8001; keepalive 32; } server { listen 80; server_name api.example.com; location / { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Connection ; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }4.3 负载均衡策略Nginx支持多种负载均衡算法upstream backend { # 轮询默认 server backend1.example.com; server backend2.example.com; # 加权轮询 server backend3.example.com weight3; # IP哈希 ip_hash; server backend4.example.com; # 最少连接 least_conn; server backend5.example.com; }5. 性能调优与问题排查5.1 性能优化参数# 文件描述符缓存 open_file_cache max1000 inactive20s; 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 4 4k; # 超时设置 client_body_timeout 12; client_header_timeout 12; send_timeout 10;5.2 常见问题排查502 Bad Gateway错误检查后端服务是否正常运行调整proxy_connect_timeout和proxy_read_timeout值验证防火墙设置地址已在使用Address already in usesudo lsof -i :80 # 查看端口占用情况 sudo kill -9 PID # 结束占用进程性能瓶颈分析# 查看Nginx状态 nginx -t # 测试配置 nginx -V # 查看编译参数 # 监控连接状态 netstat -anp | grep nginx ss -ant | grep ESTAB | wc -l5.3 日志分析技巧使用awk快速分析访问日志# 统计HTTP状态码 awk {print $9} access.log | sort | uniq -c | sort -rn # 统计访问量最高的IP awk {print $1} access.log | sort | uniq -c | sort -rn | head -20 # 统计耗时最长的请求 awk {print $NF,$7} access.log | sort -rn | head -206. 安全加固实践6.1 基础安全配置# 禁用不安全的HTTP方法 if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 405; } # 防止目录遍历 location ~* \.(env|log|htaccess)$ { deny all; } # 限制敏感文件访问 location /wp-login.php { allow 192.168.1.0/24; deny all; }6.2 防DDoS配置# 限制连接速率 limit_req_zone $binary_remote_addr zoneone:10m rate10r/s; server { location / { limit_req zoneone burst20 nodelay; } } # 限制并发连接数 limit_conn_zone $binary_remote_addr zoneaddr:10m; server { location / { limit_conn addr 10; } }6.3 WAF规则示例使用NginxLua实现基础WAF功能http { lua_shared_dict waf_rules 10m; init_by_lua_block { local waf_rules { {ruleselect.(from|limit), msgSQL injection attempt}, {rulescript, msgXSS attempt} } ngx.shared.waf_rules:set(rules, waf_rules) } server { location / { access_by_lua_block { local rules ngx.shared.waf_rules:get(rules) for _, rule in ipairs(rules) do if ngx.var.request_uri:match(rule.rule) then ngx.log(ngx.WARN, WAF blocked: ..rule.msg) return ngx.exit(403) end end } } } }7. 实用维护技巧7.1 配置管理建议模块化配置# 主配置文件 include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*;版本控制将Nginx配置纳入Git版本控制使用分支管理不同环境配置提交信息注明修改目的和影响配置检查与重载nginx -t nginx -s reload7.2 性能监控方案启用stub_status模块location /nginx_status { stub_status; allow 127.0.0.1; deny all; }Prometheus监控配置location /metrics { access_log off; stub_status; allow 192.168.1.0/24; deny all; }关键监控指标Active connectionsRequests per secondConnection acceptance rateUpstream response times7.3 自动化部署方案使用Ansible部署Nginx的示例playbook- hosts: webservers become: yes tasks: - name: Install dependencies apt: name: {{ item }} state: present with_items: - build-essential - libpcre3-dev - zlib1g-dev - libssl-dev - name: Download Nginx get_url: url: http://nginx.org/download/nginx-1.25.3.tar.gz dest: /tmp/nginx.tar.gz - name: Extract Nginx unarchive: src: /tmp/nginx.tar.gz dest: /tmp/ remote_src: yes - name: Configure and install Nginx command: | cd /tmp/nginx-1.25.3 ./configure --prefix/usr/local/nginx \ --with-http_ssl_module \ --with-http_stub_status_module make make install - name: Create systemd service template: src: templates/nginx.service.j2 dest: /etc/systemd/system/nginx.service - name: Start and enable Nginx systemd: name: nginx state: started enabled: yes
返回列表