面试题手册

梳理高频技术问题,帮助你按主题复习和查漏补缺。

服务端阅读 05月27日 22:11

Nginx 反向代理怎么配置?

Nginx 反向代理怎么配置?反向代理是 Nginx 最核心的用途之一:客户端请求先到 Nginx,再由 Nginx 转发给后端服务器,客户端感知不到真实后端的存在。和正向代理(代理客户端出国)相反,反向代理代理的是服务端。最小可用配置server { listen 80; server_name example.com; location / { proxy_pass http://192.168.1.100:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }}proxy_pass 指定后端地址,三条 proxy_set_header 是标配——不带这些头,后端拿到的全是 Nginx 的 IP,日志和鉴权都会出问题。多后端负载均衡upstream backend { server 192.168.1.100:8080 weight=3; server 192.168.1.101:8080 weight=1; server 192.168.1.102:8080 backup;}server { listen 80; location / { proxy_pass http://backend; }}四种策略选哪个?轮询(默认)无状态通用;ip_hash 保会话粘性但分布不均;least_conn 适合长连接;加权轮询按机器性能分配。生产环境常用加权轮询 + 健康检查。WebSocket 代理location /ws/ { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_read_timeout 3600s;}不加 Upgrade 头,WebSocket 握手直接失败;proxy_read_timeout 不加长,空闲连接会被 Nginx 主动断开,这是最常见的踩坑点。面试追问:反向代理和正向代理的区别?反向代理代理服务端,客户端不知道真实后端是谁;正向代理代理客户端,服务端不知道真实客户端是谁。一句话:正向代理帮客户端藏身份,反向代理帮服务端藏身份。生产环境别漏这些超时三件套:proxy_connect_timeout、proxy_send_timeout、proxy_read_timeout,默认 60s,慢接口要调大缓冲默认开着,大文件上传场景注意 proxy_buffer_size 和 proxy_buffers 调大HTTPS 场景在 Nginx 做 SSL 终止,后端走内网 HTTP,证书只管 Nginx 一层proxy_redirect off 防止后端 302 重定向把内网地址暴露给客户端
服务端阅读 05月27日 22:10

Nginx 如何配置 HTTPS 和 SSL 证书?

答案Nginx 启用 HTTPS 的核心是在 server 块中监听 443 端口并指定证书与私钥路径:server { listen 443 ssl http2; server_name example.com; ssl_certificate /etc/nginx/ssl/example.com.crt; ssl_certificate_key /etc/nginx/ssl/example.com.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m;}同时配置 HTTP 自动跳转 HTTPS:server { listen 80; server_name example.com; return 301 https://$host$request_uri;}追问一:SSL 证书有哪些类型?怎么选?自签名证书:测试用,浏览器不信任Let's Encrypt:免费 DV 证书,90 天有效期,Certbot 自动申请与续期商业证书(OV/EV):CA 机构签发,验证组织身份,适合生产环境Let's Encrypt 申请示例:sudo certbot --nginx -d example.com -d www.example.com追问二:如何提升 HTTPS 安全性?四个关键措施:仅启用 TLS 1.2+,禁用 SSLv3 和 TLS 1.0HSTS 头,防止降级攻击:add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;OCSP Stapling,减少证书验证延迟:ssl_stapling on; ssl_stapling_verify on;强密钥,至少 2048 位 RSA 或 256 位 ECC追问三:证书链不完整怎么办?浏览器验证证书需要完整的信任链。若缺少中间证书,需将服务器证书与中间证书合并:cat example.com.crt intermediate.crt > bundle.crtNginx 中指向合并后的文件:ssl_certificate /etc/nginx/ssl/bundle.crt;追问四:多域名如何共用证书?通配符证书(*.example.com)覆盖子域SAN 证书支持多个域名,Certbot 申请时加多个 -d 参数SNI(Server Name Indication)让同一 IP 托管多张证书,Nginx 原生支持配置验证用 nginx -t,无停机重载用 nginx -s reload。
服务端阅读 05月27日 21:52

Nginx 的事件驱动模型是什么?如何实现高并发?

答案Nginx 采用事件驱动 + 非阻塞 I/O 模型,核心是 Master-Worker 进程架构 + epoll 事件循环。每个 Worker 进程单线程运行一个事件循环,通过 epoll 同时监听数千个连接的读写事件,事件就绪时回调处理,I/O 等待期间不阻塞进程,从而用少量进程支撑数万并发连接。事件驱动核心机制epoll 的工作方式:内核维护一个就绪队列,只有活跃连接才会触发事件通知,时间复杂度 O(1)。与传统 select/poll 的 O(n) 轮询不同,epoll 不受 FD 数量影响——这正是 Nginx 解决 C10K 问题的根基。事件循环流程:Worker 进程启动 → 注册监听 FD 到 epoll → epoll_wait 阻塞等待事件 → 事件就绪返回 → 回调处理(accept/read/write) → 继续 epoll_wait连接状态机:每个连接在 Worker 内部以状态机方式管理,经历 等待读 → 处理请求 → 等待写 → 发送响应 → 等待新请求(keepalive) 的状态转换,I/O 等待时让出 CPU 给其他连接处理。Master-Worker 进程模型worker_processes auto; # 通常等于 CPU 核心数worker_rlimit_nofile 65535; # 文件描述符上限events { worker_connections 10240; # 单 Worker 最大连接数 use epoll; # Linux 选择 epoll multi_accept on; # 一次 accept 多个连接 accept_mutex off; # 高并发下关闭,减少锁争用}Master:管理 Worker 生命周期,加载配置,不处理业务请求Worker:各自独立运行事件循环,互不干扰,进程隔离保证稳定性理论并发:worker_processes × worker_connections,4 Worker × 10240 = 40960 并发与 Apache 的本质区别| 对比维度 | Nginx | Apache (prefork) ||---------|-------|------------------|| 模型 | 事件驱动,非阻塞 | 每连接一个进程,阻塞 || 内存 | 10 连接 vs 10 连点约 2MB | 10 连接约 200MB || C10K | 原生支持 | 受限于进程数 || 上下文切换 | 极少 | 频繁 |高并发调优关键参数worker_processes:设为 auto 或 CPU 核心数worker_connections:根据内存调整,通常 10240-65535accept_mutex:高并发下关闭(off),低并发开启防惊群系统级:fs.file-max、net.core.somaxconn、tcp_tw_reuse追问epoll 的 LT 和 ET 模式有什么区别?Nginx 默认用哪个? — LT 水平触发会重复通知,ET 边沿触发只通知一次,Nginx 默认 LT,配合非阻塞 I/O 确保数据读完为什么 Worker 单线程还能处理上万连接? — 因为 99% 时间连接在等 I/O,事件驱动只在 I/O 就绪时才占用 CPUaccept_mutex 是什么?什么时候该关? — 惊群控制锁,防止所有 Worker 同时争抢新连接。连接数远大于 Worker 数时关闭可提升吞吐
服务端阅读 05月27日 21:45

Nginx 的负载均衡有哪些策略?如何配置?

Nginx 负载均衡有哪些策略?如何配置?Nginx 通过 upstream 模块实现负载均衡,内置 5 种策略,另有第三方扩展策略。面试核心答案:轮询(默认)、加权轮询、最少连接、IP 哈希、一致性哈希。1. 轮询(Round Robin,默认)按顺序依次分配请求,服务器性能相近时使用。upstream backend { server 192.168.1.100:8080; server 192.168.1.101:8080;}2. 加权轮询(Weighted Round Robin)权重越高分配越多,适用于服务器性能不均。upstream backend { server 192.168.1.100:8080 weight=3; server 192.168.1.101:8080 weight=1;}3. 最少连接(Least Connections)将请求分给当前活动连接数最少的服务器,适用于请求处理时间差异大的场景。upstream backend { least_conn; server 192.168.1.100:8080; server 192.168.1.101:8080;}4. IP 哈希(IP Hash)同一客户端 IP 始终分配到同一台服务器,实现会话保持。upstream backend { ip_hash; server 192.168.1.100:8080; server 192.168.1.101:8080;}注意:ip_hash 在后端服务器增减时会导致大量请求重新分配,一致性哈希可解决此问题。5. 一致性哈希(Hash)基于指定 key(如 URI、Cookie)做哈希,consistent 参数启用一致性哈希算法,减少服务器变动时的映射抖动。upstream backend { hash $request_uri consistent; server 192.168.1.100:8080; server 192.168.1.101:8080;}服务器状态参数upstream backend { server 192.168.1.100:8080 weight=3 max_fails=3 fail_timeout=30s; server 192.168.1.101:8080 weight=2 max_fails=3 fail_timeout=30s; server 192.168.1.102:8080 down; # 永久下线 server 192.168.1.103:8080 backup; # 备用,主服务不可用时启用 server 192.168.1.104:8080 max_conns=100; # 最大并发连接数}策略选择速查| 场景 | 推荐策略 ||---|---|| 服务器性能相近 | 轮询 || 服务器性能不均 | 加权轮询 || 请求处理时间差异大 | 最少连接 || 需要会话保持 | IP 哈希 / 一致性哈希 || 需要缓存命中 | 一致性哈希(基于 URI) |完整配置示例http { upstream backend { least_conn; server 192.168.1.100:8080 weight=3 max_fails=3 fail_timeout=30s; server 192.168.1.101:8080 weight=2 max_fails=3 fail_timeout=30s; server 192.168.1.103:8080 backup; keepalive 32; } server { listen 80; server_name 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; } }}健康检查开源版 Nginx 仅支持被动健康检查(通过 max_fails / fail_timeout 判断),商业版 Nginx Plus 提供主动健康检查。面试追问Q:iphash 和一致性哈希的区别?iphash 以客户端 IP 为 key,后端变动时映射大规模失效;一致性哈希通过虚拟环减少变动影响,且可自定义 key(URI、Cookie 等),灵活性更高。Q:Nginx 负载均衡能做四层转发吗?能。使用 stream 模块可做 TCP/UDP 四层负载均衡,配置方式与 HTTP 的 upstream 类似。Q:如何实现更精细的会话保持?Nginx Plus 支持 sticky cookie 指令;开源版可配合一致性哈希 hash $cookie_jsessionid consistent 实现基于 Cookie 的会话粘滞。
服务端阅读 02月21日 16:58

Nginx 如何优化静态资源?有哪些优化策略?

Nginx 如何优化静态资源?有哪些优化策略?Nginx 在提供静态资源方面表现优异,通过合理的配置可以显著提升静态资源的加载速度和用户体验。启用高效文件传输:http { # 启用 sendfile sendfile on; # 启用 tcp_nopush tcp_nopush on; # 启用 tcp_nodelay tcp_nodelay on; server { listen 80; server_name example.com; root /var/www/html; location / { try_files $uri $uri/ =404; } }}Gzip 压缩:http { # 启用 Gzip gzip on; gzip_vary on; gzip_min_length 1024; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss application/rss+xml application/atom+xml image/svg+xml; gzip_disable "msie6"; # 静态资源预压缩 gzip_static on; server { listen 80; server_name example.com; root /var/www/html; location / { try_files $uri $uri/ =404; } }}浏览器缓存:server { listen 80; server_name example.com; root /var/www/html; # 静态资源长期缓存 location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2|ttf|eot)$ { expires 1y; add_header Cache-Control "public, immutable"; access_log off; } # HTML 文件短期缓存 location ~* \.html$ { expires 1h; add_header Cache-Control "public, must-revalidate"; } # 不缓存动态内容 location ~* \.php$ { expires off; add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0"; } location / { try_files $uri $uri/ =404; }}文件缓存:http { # 打开文件缓存 open_file_cache max=100000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on; server { listen 80; server_name example.com; root /var/www/html; location / { try_files $uri $uri/ =404; } }}静态资源分离:server { listen 80; server_name example.com; # 主站点 location / { root /var/www/html; try_files $uri $uri/ =404; } # 静态资源 location /static/ { root /var/www/static; expires 1y; add_header Cache-Control "public, immutable"; access_log off; } # 图片资源 location /images/ { root /var/www/images; expires 1y; add_header Cache-Control "public, immutable"; access_log off; } # 字体文件 location /fonts/ { root /var/www/fonts; expires 1y; add_header Cache-Control "public, immutable"; access_log off; add_header Access-Control-Allow-Origin *; }}CDN 集成:server { listen 80; server_name example.com; root /var/www/html; # 重写静态资源 URL 到 CDN location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2)$ { return 301 https://cdn.example.com$request_uri; } location / { try_files $uri $uri/ =404; }}图片优化:server { listen 80; server_name example.com; root /var/www/html; # 图片缓存 location ~* \.(jpg|jpeg|png|gif|ico|svg|webp)$ { expires 1y; add_header Cache-Control "public, immutable"; access_log off; # WebP 支持 if ($http_accept ~* "webp") { rewrite ^(.+)\.(jpg|png)$ $1.webp last; } } # 图片防盗链 location ~* \.(jpg|jpeg|png|gif)$ { valid_referers none blocked example.com *.example.com; if ($invalid_referer) { return 403; } } location / { try_files $uri $uri/ =404; }}字体文件优化:server { listen 80; server_name example.com; root /var/www/html; # 字体文件 location ~* \.(woff|woff2|ttf|otf|eot)$ { expires 1y; add_header Cache-Control "public, immutable"; access_log off; # CORS 支持 add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods "GET, OPTIONS"; add_header Access-Control-Allow-Headers "Origin, Content-Type"; } location / { try_files $uri $uri/ =404; }}静态资源预加载:server { listen 80; server_name example.com; root /var/www/html; location = / { add_header Link "</style.css>; rel=preload; as=style, </script.js>; rel=preload; as=script, </image.jpg>; rel=preload; as=image"; try_files $uri $uri/ =404; } location / { try_files $uri $uri/ =404; }}HTTP/2 推送:server { listen 443 ssl http2; server_name example.com; ssl_certificate /etc/nginx/ssl/example.com.crt; ssl_certificate_key /etc/nginx/ssl/example.com.key; root /var/www/html; # HTTP/2 推送 location = / { http2_push /style.css; http2_push /script.js; http2_push /image.jpg; try_files $uri $uri/ =404; } location / { try_files $uri $uri/ =404; }}静态资源合并:# 使用第三方模块 ngx_http_concat_moduleserver { listen 80; server_name example.com; root /var/www/html; # CSS 合并 location /static/css/ { concat on; concat_types text/css; concat_unique on; concat_max_files 10; } # JS 合并 location /static/js/ { concat on; concat_types application/javascript; concat_unique on; concat_max_files 10; } location / { try_files $uri $uri/ =404; }}完整静态资源优化配置:user nginx;worker_processes auto;worker_rlimit_nofile 65535;events { worker_connections 10240; use epoll; multi_accept on;}http { # 基础优化 sendfile on; tcp_nopush on; tcp_nodelay on; # Gzip 压缩 gzip on; gzip_vary on; gzip_min_length 1024; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss application/rss+xml application/atom+xml image/svg+xml; gzip_disable "msie6"; gzip_static on; # 文件缓存 open_file_cache max=100000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on; # 静态资源长期缓存 map $sent_http_content_type $expires { default off; text/html 1h; text/css 1y; application/javascript 1y; ~image/ 1y; ~font/ 1y; } server { listen 80; server_name example.com; root /var/www/html; index index.html; # 静态资源优化 location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2|ttf|eot)$ { expires $expires; add_header Cache-Control "public, immutable"; access_log off; } # 字体文件 CORS location ~* \.(woff|woff2|ttf|otf|eot)$ { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods "GET, OPTIONS"; add_header Access-Control-Allow-Headers "Origin, Content-Type"; } # 图片防盗链 location ~* \.(jpg|jpeg|png|gif)$ { valid_referers none blocked example.com *.example.com; if ($invalid_referer) { return 403; } } # 主路由 location / { try_files $uri $uri/ =404; } # 禁止访问隐藏文件 location ~ /\. { deny all; access_log off; log_not_found off; } }}静态资源优化最佳实践:启用压缩:使用 Gzip 压缩文本资源合理缓存:根据资源类型设置缓存时间文件分离:将静态资源分离到独立域名或 CDN预压缩:使用 gzip_static 预压缩静态文件HTTP/2:启用 HTTP/2 提升加载速度图片优化:使用 WebP 格式,启用图片压缩字体优化:使用 WOFF2 格式,启用 CORS监控性能:使用 Lighthouse 等工具监控性能定期清理:清理未使用的静态资源版本控制:使用文件名哈希实现缓存更新
服务端阅读 02月21日 16:58

Nginx 如何处理动态内容?有哪些配置方式?

Nginx 如何处理动态内容?有哪些配置方式?Nginx 本身不处理动态内容,而是通过 FastCGI、uWSGI、SCGI 等协议将请求转发给后端应用服务器处理。FastCGI 配置(PHP):server { listen 80; server_name example.com; root /var/www/html; index index.php index.html; # PHP 文件处理 location ~ \.php$ { try_files $uri =404; fastcgi_pass unix:/var/run/php/php8.0-fpm.sock; fastcgi_index index.php; # FastCGI 参数 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; include fastcgi_params; # 超时设置 fastcgi_connect_timeout 60s; fastcgi_send_timeout 60s; fastcgi_read_timeout 60s; # 缓冲区设置 fastcgi_buffer_size 4k; fastcgi_buffers 8 4k; } location / { try_files $uri $uri/ /index.php?$query_string; }}uWSGI 配置(Python):upstream django_backend { server unix:/var/run/uwsgi/app.sock; server 127.0.0.1:8000;}server { listen 80; server_name example.com; root /var/www/html; location / { uwsgi_pass django_backend; include uwsgi_params; # uWSGI 参数 uwsgi_param UWSGI_SCHEME $scheme; uwsgi_param SERVER_NAME $server_name; uwsgi_param REMOTE_ADDR $remote_addr; # 超时设置 uwsgi_connect_timeout 60s; uwsgi_send_timeout 60s; uwsgi_read_timeout 60s; # 缓冲区设置 uwsgi_buffering on; uwsgi_buffer_size 4k; uwsgi_buffers 8 4k; } # 静态文件 location /static/ { alias /var/www/html/static/; expires 1y; add_header Cache-Control "public, immutable"; }}SCGI 配置(Ruby):upstream rails_backend { server unix:/var/run/scgi/rails.sock; server 127.0.0.1:9000;}server { listen 80; server_name example.com; root /var/www/html; location / { scgi_pass rails_backend; include scgi_params; # SCGI 参数 scgi_param SCGI 1; scgi_param SERVER_SOFTWARE nginx; # 超时设置 scgi_connect_timeout 60s; scgi_send_timeout 60s; scgi_read_timeout 60s; }}HTTP 代理配置:upstream nodejs_backend { server 127.0.0.1:3000; server 127.0.0.1:3001;}server { listen 80; server_name example.com; location / { proxy_pass http://nodejs_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; proxy_set_header X-Forwarded-Proto $scheme; # 超时设置 proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; # 缓冲区设置 proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 4k; # WebSocket 支持 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }}FastCGI 缓存:# 定义 FastCGI 缓存fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=fastcgi_cache:10m max_size=1g inactive=60m;server { listen 80; server_name example.com; root /var/www/html; location ~ \.php$ { try_files $uri =404; # 启用 FastCGI 缓存 fastcgi_cache fastcgi_cache; fastcgi_cache_valid 200 60m; fastcgi_cache_valid 404 1m; fastcgi_cache_key "$scheme$request_method$host$request_uri"; # 缓存跳过条件 fastcgi_cache_bypass $skip_cache; fastcgi_no_cache $skip_cache; fastcgi_pass unix:/var/run/php/php8.0-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; # 添加缓存状态头 add_header X-Cache-Status $upstream_cache_status; }}动态内容负载均衡:upstream php_backend { least_conn; server 192.168.1.100:9000 weight=3; server 192.168.1.101:9000 weight=2; server 192.168.1.102:9000 weight=1; keepalive 32;}server { listen 80; server_name example.com; root /var/www/html; location ~ \.php$ { fastcgi_pass php_backend; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; }}动态内容压缩:http { # 启用 Gzip 压缩 gzip on; gzip_vary on; gzip_min_length 1024; gzip_comp_level 6; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml application/rss+xml; server { listen 80; server_name example.com; root /var/www/html; location ~ \.php$ { fastcgi_pass unix:/var/run/php/php8.0-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }}动态内容安全:server { listen 80; server_name example.com; root /var/www/html; # 禁止访问敏感文件 location ~* \.(htaccess|htpasswd|ini|log|sh|sql|bak|old|swp|tmp)$ { deny all; access_log off; } # PHP 文件处理 location ~ \.php$ { # 防止 PHP 文件上传执行 if ($request_filename ~* \.(jpg|jpeg|png|gif|ico)$) { return 403; } fastcgi_pass unix:/var/run/php/php8.0-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; # 限制请求大小 client_max_body_size 10m; } location / { try_files $uri $uri/ /index.php?$query_string; }}动态内容监控:# 自定义日志格式log_format dynamic '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' 'rt=$request_time uct="$upstream_connect_time" ' 'uht="$upstream_header_time" urt="$upstream_response_time" ' 'cache=$upstream_cache_status';server { listen 80; server_name example.com; root /var/www/html; access_log /var/log/nginx/dynamic.log dynamic; location ~ \.php$ { fastcgi_pass unix:/var/run/php/php8.0-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; # 添加性能头 add_header X-Response-Time $request_time; add_header X-Upstream-Time $upstream_response_time; }}完整动态内容配置示例:user nginx;worker_processes auto;http { # FastCGI 缓存 fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=fastcgi_cache:10m max_size=1g inactive=60m; # Gzip 压缩 gzip on; gzip_vary on; gzip_min_length 1024; gzip_comp_level 6; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml application/rss+xml; # 日志格式 log_format dynamic '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' 'rt=$request_time uct="$upstream_connect_time" ' 'uht="$upstream_header_time" urt="$upstream_response_time" ' 'cache=$upstream_cache_status'; # PHP 后端 upstream php_backend { least_conn; server 192.168.1.100:9000; server 192.168.1.101:9000; keepalive 32; } server { listen 80; server_name example.com; root /var/www/html; index index.php index.html; access_log /var/log/nginx/example.com.access.log dynamic; error_log /var/log/nginx/example.com.error.log warn; # 禁止访问敏感文件 location ~* \.(htaccess|htpasswd|ini|log|sh|sql|bak|old|swp|tmp)$ { deny all; access_log off; } # 静态资源 location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2)$ { expires 1y; add_header Cache-Control "public, immutable"; access_log off; } # PHP 文件处理 location ~ \.php$ { try_files $uri =404; # 启用缓存 fastcgi_cache fastcgi_cache; fastcgi_cache_valid 200 60m; fastcgi_cache_valid 404 1m; fastcgi_cache_key "$scheme$request_method$host$request_uri"; fastcgi_pass php_backend; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; # 超时设置 fastcgi_connect_timeout 60s; fastcgi_send_timeout 60s; fastcgi_read_timeout 60s; # 缓冲区设置 fastcgi_buffer_size 4k; fastcgi_buffers 8 4k; # 添加缓存状态头 add_header X-Cache-Status $upstream_cache_status; add_header X-Response-Time $request_time; add_header X-Upstream-Time $upstream_response_time; } # 主路由 location / { try_files $uri $uri/ /index.php?$query_string; } }}动态内容处理最佳实践:使用缓存:启用 FastCGI 缓存减少后端负载负载均衡:使用 upstream 实现负载均衡合理超时:根据业务需求设置超时时间缓冲区优化:调整缓冲区大小提升性能压缩响应:启用 Gzip 压缩减少传输数据安全配置:防止文件上传执行和敏感文件访问监控性能:记录响应时间和缓存命中率静态分离:将静态资源分离到独立路径连接保持:使用 keepalive 减少连接开销错误处理:配置友好的错误页面
服务端阅读 02月21日 16:50

Nginx 常见问题有哪些?如何进行故障排查?

Nginx 常见问题有哪些?如何进行故障排查?Nginx 在运行过程中可能会遇到各种问题,掌握故障排查方法对于快速解决问题至关重要。常见问题及解决方案:1. 502 Bad Gateway原因:后端服务不可用或连接超时排查步骤:# 检查后端服务状态systemctl status php-fpmsystemctl status nginx# 检查后端服务端口netstat -tlnp | grep :9000# 检查 Nginx 错误日志tail -f /var/log/nginx/error.log# 检查后端服务日志tail -f /var/log/php-fpm/error.log解决方案:# 增加超时时间proxy_connect_timeout 60s;proxy_send_timeout 60s;proxy_read_timeout 60s;# 检查后端服务配置fastcgi_connect_timeout 60s;fastcgi_send_timeout 60s;fastcgi_read_timeout 60s;2. 504 Gateway Timeout原因:后端服务处理时间过长排查步骤:# 检查后端服务性能top -u nginxhtop# 检查数据库连接mysql -u root -p -e "SHOW PROCESSLIST;"# 检查慢查询日志tail -f /var/log/mysql/slow.log解决方案:# 增加超时时间proxy_read_timeout 300s;fastcgi_read_timeout 300s;# 优化后端服务性能# 优化数据库查询# 增加缓存3. 403 Forbidden原因:权限不足或访问控制限制排查步骤:# 检查文件权限ls -la /var/www/html# 检查 Nginx 用户ps aux | grep nginx# 检查 SELinux 状态getenforce# 检查防火墙规则iptables -L -n解决方案:# 修改文件权限chown -R nginx:nginx /var/www/htmlchmod -R 755 /var/www/html# 临时关闭 SELinuxsetenforce 0# 添加防火墙规则firewall-cmd --add-service=http --permanentfirewall-cmd --reload4. 404 Not Found原因:文件不存在或路径配置错误排查步骤:# 检查文件是否存在ls -la /var/www/html# 检查 Nginx 配置nginx -T | grep root# 检查符号链接readlink -f /var/www/html解决方案:# 检查 root 配置server { listen 80; server_name example.com; root /var/www/html; index index.html index.php; location / { try_files $uri $uri/ =404; }}5. 413 Request Entity Too Large原因:上传文件超过限制解决方案:# 增加 client_max_body_sizeclient_max_body_size 100m;# PHP 配置# /etc/php.iniupload_max_filesize = 100Mpost_max_size = 100M6. 连接数不足原因:worker_connections 设置过小排查步骤:# 检查当前连接数netstat -an | grep :80 | wc -l# 检查 Nginx 状态curl http://localhost/nginx_status# 检查系统限制ulimit -n解决方案:# 增加连接数events { worker_connections 10240;}# 增加文件描述符限制worker_rlimit_nofile 65535;诊断工具:1. 配置测试# 测试配置文件nginx -t# 显示配置nginx -T# 检查配置语法nginx -c /etc/nginx/nginx.conf -t2. 状态监控# 启用状态页面location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all;}3. 日志分析# 实时查看错误日志tail -f /var/log/nginx/error.log# 查看最近 100 行错误tail -n 100 /var/log/nginx/error.log# 搜索特定错误grep "502" /var/log/nginx/error.log# 统计错误数量awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn4. 性能分析# 使用 strace 追踪系统调用strace -p $(pidof nginx)# 使用 tcpdump 抓包tcpdump -i eth0 port 80 -w nginx.pcap# 使用 netstat 查看连接netstat -an | grep :80 | awk '{print $6}' | sort | uniq -c性能问题排查:1. CPU 使用率高# 检查 CPU 使用top -p $(pidof nginx)# 检查 worker 进程数ps aux | grep nginx | wc -l# 检查 CPU 亲和性taskset -cp $(pidof nginx)解决方案:# 调整 worker_processesworker_processes auto;# 绑定 CPU 核心worker_cpu_affinity auto;# 启用高效文件传输sendfile on;tcp_nopush on;2. 内存使用过高# 检查内存使用free -m# 检查进程内存ps aux | grep nginx | awk '{print $6}' | awk '{sum+=$1} END {print sum}'# 检查内存泄漏valgrind --leak-check=full nginx解决方案:# 减少缓冲区大小client_body_buffer_size 128k;client_header_buffer_size 1k;# 优化连接数worker_connections 4096;# 启用文件缓存open_file_cache max=100000 inactive=20s;3. 响应慢# 检查响应时间curl -w "@curl-format.txt" -o /dev/null -s http://example.com# 检查网络延迟ping example.com# 检查 DNS 解析nslookup example.com解决方案:# 启用 Gzip 压缩gzip on;gzip_min_length 1024;# 启用缓存proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=cache:10m;# 优化 TCP 参数tcp_nodelay on;tcp_nopush on;安全问题排查:1. DDoS 攻击# 检查异常连接netstat -an | grep :80 | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -rn# 检查请求频率awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20解决方案:# 启用限流limit_req_zone $binary_remote_addr zone=limit:10m rate=10r/s;limit_req zone=limit burst=20 nodelay;# 限制连接数limit_conn_zone $binary_remote_addr zone=conn:10m;limit_conn conn 10;2. 恶意访问# 检查可疑 User-Agentgrep "bot" /var/log/nginx/access.log# 检查 SQL 注入尝试grep "union.*select" /var/log/nginx/access.log解决方案:# 阻止恶意 User-Agentif ($http_user_agent ~* (bot|crawl|spider)) { return 403;}# 防止 SQL 注入if ($args ~* "union.*select.*\(") { return 403;}监控和告警:1. 系统监控# 使用 Prometheus + Grafana# 使用 Zabbix# 使用 Nagios2. 日志监控# 使用 ELK Stack# 使用 Graylog# 使用 Fluentd3. 自动告警# 使用 Alertmanager# 使用 PagerDuty# 使用 Slack 集成最佳实践:定期备份配置:备份 Nginx 配置文件监控日志:实时监控错误日志性能测试:定期进行压力测试文档记录:记录常见问题和解决方案自动化部署:使用配置管理工具版本控制:使用 Git 管理配置文件定期更新:保持 Nginx 版本最新安全审计:定期进行安全检查故障排查流程:1. 确认问题现象 ↓2. 检查 Nginx 状态 ↓3. 查看错误日志 ↓4. 检查配置文件 ↓5. 检查后端服务 ↓6. 检查系统资源 ↓7. 应用解决方案 ↓8. 验证修复效果 ↓9. 记录问题和解决方案
服务端阅读 02月21日 16:50

Nginx 常见的部署架构有哪些?如何选择合适的架构?

Nginx 常见的部署架构有哪些?如何选择合适的架构?Nginx 可以根据不同的业务需求和规模采用多种部署架构,从单机部署到分布式集群都有相应的解决方案。单机部署架构:客户端 → Nginx → 应用服务器 → 数据库适用场景:小型网站或应用开发测试环境低流量业务配置示例:server { listen 80; server_name example.com; root /var/www/html; index index.php index.html; location ~ \.php$ { fastcgi_pass unix:/var/run/php/php8.0-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location / { try_files $uri $uri/ =404; }}反向代理架构:客户端 → Nginx (反向代理) → 后端服务器集群适用场景:多个应用服务器需要统一入口需要负载均衡需要隐藏后端服务器配置示例:upstream backend { server 192.168.1.100:8080 weight=3; server 192.168.1.101:8080 weight=2; server 192.168.1.102:8080 weight=1; keepalive 32;}server { listen 80; server_name 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; proxy_set_header X-Forwarded-Proto $scheme; }}负载均衡架构:客户端 → Nginx (负载均衡器) → 后端服务器池适用场景:高并发访问需要水平扩展需要高可用性负载均衡策略:# 轮询(默认)upstream backend { server 192.168.1.100:8080; server 192.168.1.101:8080;}# 最少连接upstream backend { least_conn; server 192.168.1.100:8080; server 192.168.1.101:8080;}# IP 哈希upstream backend { ip_hash; server 192.168.1.100:8080; server 192.168.1.101:8080;}# 加权轮询upstream backend { server 192.168.1.100:8080 weight=3; server 192.168.1.101:8080 weight=2; server 192.168.1.102:8080 weight=1;}多层代理架构:客户端 → 边缘 Nginx → 中间 Nginx → 应用服务器适用场景:大规模分布式系统需要多层缓存需要安全隔离配置示例:# 边缘 Nginxupstream middle_layer { server 192.168.1.200:80; server 192.168.1.201:80;}server { listen 80; server_name example.com; location / { proxy_pass http://middle_layer; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }}# 中间层 Nginxupstream backend { server 192.168.1.100:8080; server 192.168.1.101:8080;}server { listen 80; server_name middle.example.com; location / { proxy_pass http://backend; proxy_set_header Host $host; }}CDN 集成架构:客户端 → CDN → 源站 Nginx → 后端服务器适用场景:全球用户访问需要加速静态资源需要减轻源站压力配置示例:server { listen 80; server_name example.com; # 静态资源重定向到 CDN location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2)$ { return 301 https://cdn.example.com$request_uri; } # 动态内容 location / { proxy_pass http://backend; proxy_set_header Host $host; }}高可用架构(Keepalived + Nginx):客户端 → VIP (虚拟IP) ↓ Nginx 主节点 ← Keepalived ↓ Nginx 备节点 ← Keepalived ↓ 后端服务器适用场景:需要高可用性不能接受单点故障关键业务系统配置示例:# 主节点 Nginx 配置upstream backend { server 192.168.1.100:8080; server 192.168.1.101:8080;}server { listen 80; server_name example.com; location / { proxy_pass http://backend; proxy_set_header Host $host; }}# Keepalived 配置vrrp_instance VI_1 { state MASTER interface eth0 virtual_router_id 51 priority 100 advert_int 1 authentication { auth_type PASS auth_pass 1234 } virtual_ipaddress { 192.168.1.50 }}微服务架构:客户端 → Nginx (API 网关) → 微服务集群适用场景:微服务架构需要统一 API 入口需要服务发现配置示例:# 用户服务upstream user_service { server 192.168.1.100:8080; server 192.168.1.101:8080;}# 订单服务upstream order_service { server 192.168.1.200:8080; server 192.168.1.201:8080;}# 支付服务upstream payment_service { server 192.168.1.300:8080; server 192.168.1.301:8080;}server { listen 80; server_name api.example.com; # 路由到用户服务 location /api/users/ { proxy_pass http://user_service; proxy_set_header Host $host; } # 路由到订单服务 location /api/orders/ { proxy_pass http://order_service; proxy_set_header Host $host; } # 路由到支付服务 location /api/payments/ { proxy_pass http://payment_service; proxy_set_header Host $host; }}缓存架构:客户端 → Nginx (缓存层) → 后端服务器适用场景:读多写少的应用需要减轻后端压力需要提升响应速度配置示例:# 定义缓存路径proxy_cache_path /var/cache/nginx/proxy levels=1:2 keys_zone=proxy_cache:10m max_size=1g inactive=60m;upstream backend { server 192.168.1.100:8080; server 192.168.1.101:8080;}server { listen 80; server_name example.com; location / { # 启用缓存 proxy_cache proxy_cache; proxy_cache_valid 200 10m; proxy_cache_valid 404 1m; proxy_cache_key "$scheme$request_method$host$request_uri"; # 缓存跳过条件 proxy_cache_bypass $http_cache_control; proxy_no_cache $http_cache_control; proxy_pass http://backend; proxy_set_header Host $host; # 添加缓存状态头 add_header X-Cache-Status $upstream_cache_status; }}混合架构:客户端 → Nginx (静态资源) → CDN ↓ Nginx (动态内容) → 应用服务器适用场景:复杂业务系统需要分离静态和动态内容需要多种优化策略配置示例:# 静态资源服务器server { listen 80; server_name static.example.com; root /var/www/static; location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2)$ { expires 1y; add_header Cache-Control "public, immutable"; access_log off; }}# 动态内容服务器upstream backend { server 192.168.1.100:8080; server 192.168.1.101:8080;}server { listen 80; server_name example.com; location / { proxy_pass http://backend; proxy_set_header Host $host; }}架构选择指南:| 业务需求 | 推荐架构 | 说明 ||---------|-----------|------|| 小型网站 | 单机部署 | 简单易维护 || 中型应用 | 反向代理 | 统一入口,负载均衡 || 高并发 | 负载均衡架构 | 水平扩展,高可用 || 全球业务 | CDN 集成架构 | 加速访问,减轻源站压力 || 关键业务 | 高可用架构 | 避免单点故障 || 微服务 | 微服务架构 | 统一 API 网关 || 读多写少 | 缓存架构 | 提升性能,减轻后端压力 |部署架构最佳实践:渐进式扩展:从简单架构开始,根据需求逐步扩展监控告警:实时监控架构状态,及时发现问题容灾备份:配置备份和容灾方案安全防护:在架构各层添加安全措施性能优化:根据业务特点选择合适的优化策略文档记录:详细记录架构设计和配置定期演练:定期进行故障演练,验证架构可靠性成本控制:在满足需求的前提下控制成本
服务端阅读 02月21日 16:45

什么是 Nginx?它的主要特点是什么?

什么是 Nginx?它的主要特点是什么?Nginx 是一个高性能的 HTTP 和反向代理服务器,同时也是一个 IMAP/POP3 代理服务器。它由 Igor Sysoev 开发,最初发布于2004年,旨在解决 C10k 问题,即同时处理大量客户端连接的需求。Nginx 的主要特点:高性能:采用事件驱动架构,能够处理数以万计的并发连接,内存占用低稳定性强:在高并发环境下表现稳定,能够长时间运行而不崩溃反向代理:可以作为反向代理服务器,将请求转发到后端服务器负载均衡:支持多种负载均衡算法,如轮询、最少连接、IP 哈希等静态文件服务:高效地提供静态文件服务,如 HTML、CSS、JavaScript、图片等缓存功能:支持 FastCGI、uWSGI、SCGI、memcached 等缓存SSL/TLS 支持:支持 HTTPS 协议,可以配置 SSL 证书模块化设计:通过模块扩展功能,支持第三方模块热部署:支持在不中断服务的情况下重新加载配置跨平台:支持 Linux、Windows、macOS 等多种操作系统与 Apache 的区别:Nginx 采用事件驱动、非阻塞 I/O 模型,Apache 采用进程/线程模型Nginx 在高并发场景下性能更好,资源消耗更低Apache 模块更丰富,动态处理能力更强Nginx 配置相对简单,学习曲线较平缓适用场景:高并发 Web 服务器反向代理服务器负载均衡器静态资源服务器API 网关WebSocket 代理
前端阅读 602024年7月15日 23:58

如何动态修改 nginx 的配置信息?

动态配置 Nginx 的方法确实,动态配置 Nginx 是在不重启服务的情况下更改配置的实用能力。这对于需要高可用性的生产环境尤其重要。以下是几种可以实现动态配置Nginx的方法:1. 使用 nginx -s reload这是最常见的动态修改Nginx配置的方法。修改完nginx的配置文件后,可以使用 nginx -s reload 命令来重新加载配置文件,这样做可以不中断服务。这个命令实际上会启动新的worker进程,并逐渐停止旧的worker进程。例如:sudo nginx -s reload2. 使用 Consul 和 Consul TemplateConsul 是一个服务网络解决方案,可以用来动态地处理服务发现和配置。搭配使用 Consul Template 可以动态生成Nginx配置文件。Consul Template 监控Consul的状态变化,一旦检测到变化,就会重新渲染配置模板并重新加载Nginx。这种方法适用于基于服务发现的动态配置场景。3. 使用 OpenRestyOpenResty 是一个基于Nginx与Lua的动态web平台,它允许通过编写Lua脚本来动态地更改配置逻辑。例如,可以在access阶段根据请求的不同动态改变代理服务器或者其他配置。这种方法提供了极高的灵活性。4. 使用 Docker 容器在Docker容器中运行Nginx时,可以通过更新Docker容器的配置来实现Nginx的动态配置。这通常涉及到使用环境变量或挂载配置卷来修改配置。容器化管理工具(如Kubernetes)可以在不停机的情况下滚动更新Nginx配置。5. 动态模块Nginx也支持动态模块,这些模块可以在不重新编译Nginx的情况下加载或卸载。这使得用户可以根据需要添加或删除功能,虽然这不直接修改Nginx的配置文件,但它提供了一种方式来扩展Nginx的功能而不需要重启服务。结论动态配置Nginx主要目的是减少因配置更改而导致的服务中断。上述方法各有优势,适用于不同的场景和需求。在选择具体的实现方式时,应评估实际的业务需求、资源和技术栈。