找回密码
 立即注册
首页 业界区 安全 Ngnix基础知识简易科普

Ngnix基础知识简易科普

决任愧 3 天前
0.什么是Nginx?

Nginx(发音为 "engine-x")是一款高性能的 HTTP 服务器和反向代理服务器,同时也可用作邮件代理服务器和通用的 TCP/UDP 代理服务器。它由俄罗斯工程师 Igor Sysoev 于 2002 年开始开发,2004 年首次公开发布,旨在解决当时流行的 Apache HTTP Server 在高并发场景下的性能瓶颈。如今,Nginx 已成为全球最流行的 Web 服务器之一,被大量高流量网站(如 Netflix、GitHub、WordPress.com)所采用。
0.1 核心特性


  • 高并发、低内存占用
    Nginx 采用异步、非阻塞的事件驱动架构,能够在单台服务器上处理数以万计的并发连接,而内存消耗远低于传统的基于进程/线程的模型。
  • 反向代理与负载均衡
    作为反向代理,Nginx 可以将客户端请求分发到后端服务器(如应用服务器、数据库),并支持多种负载均衡算法(轮询、最少连接、IP 哈希等),实现高可用和水平扩展。
  • 静态文件服务
    Nginx 在处理静态文件(HTML、CSS、JavaScript、图片等)方面非常高效,能够直接发送文件而不占用过多的内存和 CPU。
  • SSL/TLS 终止
    支持 HTTP/2、HTTPS,可以集中管理 SSL 证书,对后端服务透明,减轻后端服务的加密负担。
  • 缓存机制
    内置强大的缓存功能,可以缓存后端响应,加速内容分发,降低后端压力。
  • 模块化设计
    核心功能精简,通过模块扩展。官方提供了丰富的模块(如 ngx_http_proxy_module、ngx_http_ssl_module),也支持第三方模块。
  • 高可靠性
    主进程与工作进程分离,主进程负责管理,工作进程处理请求。即使某个工作进程崩溃,主进程也能立即启动新的工作进程,保证服务持续可用。
0.2 架构解析

Nginx 的架构基于 事件驱动(event-driven) 和 非阻塞(non-blocking) 模型,具体实现依赖于操作系统的高效机制(如 Linux 的 epoll、FreeBSD 的 kqueue)。其进程模型如下:

  • Master 进程:负责读取配置文件、绑定端口、启动和监控 Worker 进程。不处理具体请求。
  • Worker 进程:通常每个 CPU 核心对应一个 Worker 进程。Worker 进程接受连接、处理请求,通过事件循环来管理多个连接。
每个 Worker 进程可以处理成千上万个连接,因为它通过事件通知机制在单个线程中处理所有并发 I/O 操作,而不是为每个连接创建独立的进程/线程。
这种设计使得 Nginx 在处理大量长连接(如 WebSocket、HTTP/2)时表现出色。
1.什么是反向代理?

在搞清楚反向代理之前,我们了解一下正向代理。
所谓正向代理,就是当用户访问原本无法访问网站A(比如google)时,我们首先通过某个代理服务器或某个代理池充当中介从而隐藏自己真实的ip,同时因为“中介”能够直接访问网站A,所以我们可以间接地访问到网站A。生活中常见的类似例子有路由器转发、开代理池的编程、缓存、上网行为认证等。
1.png

2.png

那么反向代理是什么呢?简单来说,就是当出差在外的用户突然需要访问单位A(比如学校)的内网时,必须先经过该单位的内部代理服务器,进而转发需要传达的消息到内部的后端服务器,从而使得学校内部或公司内部的相关人员接受到准确的消息。什么时候需要用到反向代理呢?其中一个好处是当一个公司同时部署了多个服务器时,对于发送的指定消息只需要访问其中一个或少量服务器时,如果没有反向代理服务器,在公网上这些消息无法确定被发送到那个服务器,从而造成大量的浪费资源的行为。但是,如果拥有反向代理服务器,这时候被指定的消息可能需要通过内部代理服务器来进行简单的转发从而达到负载均衡的目的。否则,当内部人员的消息内容过多或者来自外部的攻击行为过于频繁,这时候多个服务器可能面临瘫痪、崩溃的局面。例外一个好处就是,当使用Ngnix/Lua等反向代理技术时,这些内部服务器无法暴露在公网上,很好的隐藏了自己的真实ip,从而公网用户无法攻击内部服务器。同时利用反向代理技术可以迅速有效地部署防火墙产品,譬如AWS、GCP、宝塔、雷池等,这些防火墙有效地保护了个人数字资产。
3.png

总结来说,就正如前面的表格比较和下方文字描述的那样。
4.png

2.常见的配置模块

这些常用模块都是由ai画图软件总结的,大家阅读的时候可能对英语阅读能力较强,笔者建议读者结合官方文档做一个参考。
2.1 SSL/TLS证书模块

5.png
  1. server {
  2.     listen 443 ssl http2;
  3.     server_name example.com;
  4.     # SSL Certificate files
  5.     ssl_certificate /etc/nginx/ssl/example.com.crt;
  6.     ssl_certificate_key /etc/nginx/ssl/example.com.key;
  7.     # SSL Protocols and Ciphers
  8.     ssl_protocols TLSv1.2 TLSv1.3;
  9.     ssl_ciphers HIGH:!aNULL:!MD5;
  10.     ssl_prefer_server_ciphers on;
  11.     # SSL Session Cache
  12.     ssl_session_cache shared:SSL:10m;
  13.     ssl_session_timeout 10m;
  14.     # HSTS (HTTP Strict Transport Security)
  15.     add_header Strict-Transport-Security "max-age=31536000" always;
  16.     location / {
  17.         proxy_pass http://backend;
  18.     }
  19. }
复制代码
2.2  gzip on 模块

6.png
  1. http {
  2.     # Enable Gzip compression
  3.     gzip on;
  4.     gzip_vary on;
  5.     gzip_proxied any;
  6.     gzip_comp_level 6;
  7.     gzip_min_length 1000;
  8.     # Specify MIME types to compress
  9.     gzip_types
  10.         text/plain
  11.         text/css
  12.         text/xml
  13.         text/javascript
  14.         application/json
  15.         application/javascript
  16.         application/xml+rss
  17.         application/rss+xml
  18.         font/truetype
  19.         font/opentype
  20.         application/vnd.ms-fontobject
  21.         image/svg+xml;
  22.     # Disable gzip for IE6
  23.     gzip_disable "msie6";
  24.     server {
  25.         listen 80;
  26.         server_name example.com;
  27.         # ... rest of config
  28.     }
  29. }
复制代码
2.3 代理池模块

7.png
  1. upstream backend {
  2.     server backend1.example.com:8080;
  3.     server backend2.example.com:8080;
  4.     server backend3.example.com:8080;
  5. }
  6. server {
  7.     listen 80;
  8.     server_name example.com;
  9.     location / {
  10.         # Basic proxy settings
  11.         proxy_pass http://backend;
  12.         
  13.         # Headers
  14.         proxy_set_header Host $host;
  15.         proxy_set_header X-Real-IP $remote_addr;
  16.         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  17.         proxy_set_header X-Forwarded-Proto $scheme;
  18.         # Buffering
  19.         proxy_buffering on;
  20.         proxy_buffer_size 4k;
  21.         proxy_buffers 8 4k;
  22.         # Timeouts
  23.         proxy_connect_timeout 60s;
  24.         proxy_send_timeout 60s;
  25.         proxy_read_timeout 60s;
  26.         # Error handling
  27.         proxy_next_upstream error timeout invalid_header http_500;
  28.     }
  29. }
复制代码
2.4 重写模块

8.png
  1. server {
  2.     listen 80;
  3.     server_name example.com www.example.com;
  4.     # Redirect www to non-www
  5.     if ($host = www.example.com) {
  6.         return 301 https://example.com$request_uri;
  7.     }
  8.     # Redirect HTTP to HTTPS
  9.     return 301 https://$host$request_uri;
  10. }
  11. server {
  12.     listen 443 ssl;
  13.     server_name example.com;
  14.     # Rewrite old URLs to new ones
  15.     rewrite ^/old-page$ /new-page permanent;
  16.     rewrite ^/blog/(.*)$ /articles/$1 permanent;
  17.     # Conditional rewrites
  18.     location /api {
  19.         # Rewrite /api/v1/users to /users
  20.         rewrite ^/api/v1/(.*)$ /$1 break;
  21.         proxy_pass http://backend;
  22.     }
  23.     # Use try_files for clean URLs
  24.     location / {
  25.         try_files $uri $uri/ /index.html;
  26.     }
  27. }
复制代码
2.5 响应头模块

9.png
  1. server {
  2.     listen 80;
  3.     server_name example.com;
  4.     # Security Headers
  5.     add_header X-Frame-Options "SAMEORIGIN" always;
  6.     add_header X-Content-Type-Options "nosniff" always;
  7.     add_header X-XSS-Protection "1; mode=block" always;
  8.     add_header Referrer-Policy "no-referrer-when-downgrade" always;
  9.     add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
  10.     # Remove headers (for security)
  11.     more_clear_headers 'Server';
  12.     more_clear_headers 'X-Powered-By';
  13.     # CORS Headers
  14.     location /api {
  15.         add_header Access-Control-Allow-Origin "*" always;
  16.         add_header Access-Control-Allow-Methods "GET, POST, OPTIONS" always;
  17.         add_header Access-Control-Allow-Headers "Authorization, Content-Type" always;
  18.         if ($request_method = 'OPTIONS') {
  19.             return 204;
  20.         }
  21.         proxy_pass http://backend;
  22.     }
  23.     # Cache Control
  24.     location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
  25.         expires 1y;
  26.         add_header Cache-Control "public, immutable";
  27.     }
  28. }
复制代码
2.6 速率限制模块

10.png
  1. http {
  2.     # Define rate limit zones
  3.     # Zone 'one' allows 10 requests per second per IP
  4.     limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
  5.    
  6.     # Zone 'api' allows 100 requests per minute per IP
  7.     limit_req_zone $binary_remote_addr zone=api:10m rate=100r/m;
  8.    
  9.     # Zone 'login' allows 5 requests per minute per IP
  10.     limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
  11.     server {
  12.         listen 80;
  13.         server_name example.com;
  14.         # General rate limiting
  15.         location / {
  16.             limit_req zone=one burst=20 nodelay;
  17.             proxy_pass http://backend;
  18.         }
  19.         # API rate limiting
  20.         location /api {
  21.             limit_req zone=api burst=50;
  22.             limit_req_status 429;
  23.             proxy_pass http://backend;
  24.         }
  25.         # Strict rate limiting for login
  26.         location /login {
  27.             limit_req zone=login burst=5;
  28.             limit_req_log_level warn;
  29.             proxy_pass http://backend;
  30.         }
  31.     }
  32. }
复制代码
2.7 镜像模块

11.png
  1. http {
  2.     # Define cache path and settings
  3.     proxy_cache_path /var/cache/nginx/data
  4.                      levels=1:2
  5.                      keys_zone=my_cache:10m
  6.                      max_size=1g
  7.                      inactive=60m
  8.                      use_temp_path=off;
  9.     server {
  10.         listen 80;
  11.         server_name example.com;
  12.         location / {
  13.             # Enable caching
  14.             proxy_cache my_cache;
  15.             
  16.             # Cache status in response header (for debugging)
  17.             add_header X-Cache-Status $upstream_cache_status;
  18.             
  19.             # Cache valid responses
  20.             proxy_cache_valid 200 302 10m;
  21.             proxy_cache_valid 404 1m;
  22.             
  23.             # Cache even with certain headers
  24.             proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
  25.             
  26.             # Cache locking
  27.             proxy_cache_lock on;
  28.             proxy_cache_lock_timeout 5s;
  29.             
  30.             # Cache key
  31.             proxy_cache_key "$scheme$request_method$host$request_uri";
  32.             
  33.             # Bypass cache for certain conditions
  34.             proxy_cache_bypass $http_pragma $http_authorization;
  35.             proxy_no_cache $http_pragma $http_authorization;
  36.             proxy_pass http://backend;
  37.         }
  38.         # Don't cache API POST requests
  39.         location /api {
  40.             proxy_cache_methods GET HEAD;
  41.             proxy_pass http://backend;
  42.         }
  43.     }
  44. }
复制代码
2.8 基础认证模块

12.png
  1. server {
  2.     listen 80;
  3.     server_name example.com;
  4.     # Protect entire site
  5.     location / {
  6.         auth_basic "Restricted Access";
  7.         auth_basic_user_file /etc/nginx/.htpasswd;
  8.         proxy_pass http://backend;
  9.     }
  10.     # Protect specific directory
  11.     location /admin {
  12.         auth_basic "Admin Area";
  13.         auth_basic_user_file /etc/nginx/.htpasswd_admin;
  14.         proxy_pass http://backend;
  15.     }
  16.     # Public location (no auth)
  17.     location /public {
  18.         auth_basic off;
  19.         proxy_pass http://backend;
  20.     }
  21.     # Conditional authentication (IP-based)
  22.     location /restricted {
  23.         satisfy any;
  24.         
  25.         # Allow from specific IPs without password
  26.         allow 192.168.1.0/24;
  27.         allow 10.0.0.0/8;
  28.         deny all;
  29.         
  30.         # Require password if not from allowed IP
  31.         auth_basic "Restricted Access";
  32.         auth_basic_user_file /etc/nginx/.htpasswd;
  33.         
  34.         proxy_pass http://backend;
  35.     }
  36. }
  37. # Create password file with:
  38. # htpasswd -c /etc/nginx/.htpasswd username
复制代码
2.9 geoIP 模块

13.png
  1. http {
  2.     # Define geo-based variables
  3.     geo $country {
  4.         default ZZ;
  5.         
  6.         # US IP ranges
  7.         1.2.3.0/24 US;
  8.         5.6.7.0/24 US;
  9.         
  10.         # UK IP ranges
  11.         10.20.30.0/24 UK;
  12.         
  13.         # Include external file
  14.         include /etc/nginx/geo.conf;
  15.     }
  16.     # Create blocking rules based on country
  17.     geo $blocked_country {
  18.         default 0;
  19.         1.2.3.0/24 1;  # Block this range
  20.     }
  21.     # Map based on geo
  22.     map $country $redirect_domain {
  23.         default example.com;
  24.         US      us.example.com;
  25.         UK      uk.example.com;
  26.         DE      de.example.com;
  27.     }
  28.     server {
  29.         listen 80;
  30.         server_name example.com;
  31.         # Block specific countries
  32.         if ($blocked_country) {
  33.             return 403 "Access denied from your location";
  34.         }
  35.         # Redirect based on country
  36.         location / {
  37.             # Use country in headers
  38.             add_header X-Country-Code $country;
  39.             
  40.             # Country-specific content
  41.             root /var/www/$country;
  42.             try_files $uri $uri/ /index.html;
  43.         }
  44.         # API endpoint that logs country
  45.         location /api {
  46.             proxy_set_header X-Country $country;
  47.             proxy_pass http://backend;
  48.         }
  49.     }
  50. }
复制代码
2.10 upstream模块

14.png
  1. http {
  2.     # Round-robin load balancing (default)
  3.     upstream backend_round_robin {
  4.         server backend1.example.com:8080;
  5.         server backend2.example.com:8080;
  6.         server backend3.example.com:8080;
  7.     }
  8.     # Least connections load balancing
  9.     upstream backend_least_conn {
  10.         least_conn;
  11.         
  12.         server backend1.example.com:8080;
  13.         server backend2.example.com:8080;
  14.         server backend3.example.com:8080;
  15.     }
  16.     # IP hash (session persistence)
  17.     upstream backend_ip_hash {
  18.         ip_hash;
  19.         
  20.         server backend1.example.com:8080;
  21.         server backend2.example.com:8080;
  22.         server backend3.example.com:8080;
  23.     }
  24.     # Weighted load balancing
  25.     upstream backend_weighted {
  26.         server backend1.example.com:8080 weight=3;
  27.         server backend2.example.com:8080 weight=2;
  28.         server backend3.example.com:8080 weight=1;
  29.     }
  30.     # Advanced configuration
  31.     upstream backend_advanced {
  32.         least_conn;
  33.         
  34.         # Primary servers
  35.         server backend1.example.com:8080 weight=5 max_fails=3 fail_timeout=30s;
  36.         server backend2.example.com:8080 weight=3 max_fails=3 fail_timeout=30s;
  37.         
  38.         # Backup server (used when primary servers are down)
  39.         server backup.example.com:8080 backup;
  40.         
  41.         # Keep alive connections
  42.         keepalive 32;
  43.         keepalive_timeout 60s;
  44.     }
  45.     server {
  46.         listen 80;
  47.         server_name example.com;
  48.         location / {
  49.             proxy_pass http://backend_advanced;
  50.             proxy_http_version 1.1;
  51.             proxy_set_header Connection "";
  52.         }
  53.     }
  54. }
复制代码
3.常见的配置错误

3.1 错误的分号

15.png
  1. server {
  2.     listen 80
  3.     server_name example.com
  4.    
  5.     location / {
  6.         proxy_pass http://backend
  7.     }
  8. }
  9. server {
  10.     listen 80;
  11.     server_name example.com;
  12.    
  13.     location / {
  14.         proxy_pass http://backend;
  15.     }
  16. }
复制代码
3.2 错误的if 声明
  1. location / {
  2.     # WRONG: Using if for redirects
  3.     if ($request_uri ~* "^/old-url") {
  4.         proxy_pass http://backend;
  5.     }
  6.    
  7.     # WRONG: Multiple conditions
  8.     if ($host != "example.com") {
  9.         rewrite ^ https://example.com$request_uri permanent;
  10.     }
  11. }
  12. # RIGHT: Use return for redirects
  13. location = /old-url {
  14.     return 301 /new-url;
  15. }
  16. # RIGHT: Use separate server block
  17. server {
  18.     listen 80;
  19.     server_name www.example.com;
  20.     return 301 https://example.com$request_uri;
  21. }
  22. server {
  23.     listen 80;
  24.     server_name example.com;
  25.     # ... normal config
  26. }
复制代码
3.3  错误的尾部斜杠传递

16.png
  1. # This keeps the /api prefix
  2. location /api {
  3.     proxy_pass http://backend;  # Wrong if you want to strip /api
  4. }
  5. # This might cause double slashes
  6. location /api/ {
  7.     proxy_pass http://backend/;  # Creates //api/endpoint
  8. }
  9. # Strip /api prefix from request
  10. location /api/ {
  11.     proxy_pass http://backend/;  # /api/users -> /users
  12. }
  13. # Keep /api prefix in request
  14. location /api {
  15.     proxy_pass http://backend;  # /api/users -> /api/users
  16. }
  17. # Rewrite to remove prefix
  18. location /api {
  19.     rewrite ^/api/(.*)$ /$1 break;
  20.     proxy_pass http://backend;
  21. }
复制代码
3.4 缺失根目录与别名理解
  1. # WRONG: Using root when alias is needed
  2. location /static {
  3.     root /var/www/assets;  # Looks for /var/www/assets/static
  4. }
  5. # WRONG: Using alias without trailing slash
  6. location /images {
  7.     alias /var/www/pics;  # Should have trailing slash
  8. }
  9. # RIGHT: Using root (appends location to path)
  10. location /static {
  11.     root /var/www;  # Serves /var/www/static
  12. }
  13. # RIGHT: Using alias (replaces location in path)
  14. location /static {
  15.     alias /var/www/assets/;  # Serves /var/www/assets/
  16. }
  17. # Alternative with root
  18. location /static {
  19.     root /var/www;
  20.     # Serves /var/www/static/
  21. }
复制代码
3.5 重复的请求头

17.png
  1. http {
  2.     add_header X-Frame-Options "DENY";
  3.    
  4.     server {
  5.         add_header X-Frame-Options "SAMEORIGIN";  # Duplicate!
  6.         
  7.         location / {
  8.             add_header X-Custom-Header "value";
  9.             proxy_pass http://backend;
  10.             # Header won't be added because proxy_pass clears headers
  11.         }
  12.     }
  13. }
  14. http {
  15.     # Don't add headers here unless needed globally
  16.    
  17.     server {
  18.         # Use 'always' to add headers even for error responses
  19.         add_header X-Frame-Options "SAMEORIGIN" always;
  20.         add_header X-Content-Type-Options "nosniff" always;
  21.         
  22.         location / {
  23.             # Headers in location are inherited
  24.             proxy_pass http://backend;
  25.             # Add location-specific headers
  26.             add_header X-Custom-Header "value" always;
  27.         }
  28.     }
  29. }
复制代码
3.6 错误的正则表达式
  1. # Case-sensitive match (might miss .JPG, .PNG)
  2. location ~ \.(jpg|png|gif)$ {
  3.     expires 30d;
  4. }
  5. # Wrong: Using = with regex
  6. location = ~ /api {
  7.     proxy_pass http://backend;
  8. }
  9. # Case-insensitive match for file extensions
  10. location ~* \.(jpg|jpeg|png|gif|ico|svg)$ {
  11.     expires 30d;
  12.     add_header Cache-Control "public, immutable";
  13. }
  14. # Exact match (fastest)
  15. location = /api {
  16.     proxy_pass http://backend;
  17. }
  18. # Regex match (case-sensitive)
  19. location ~ ^/api/v[0-9]+ {
  20.     proxy_pass http://backend;
  21. }
  22. # Regex match (case-insensitive)
  23. location ~* ^/API {
  24.     proxy_pass http://backend;
  25. }
复制代码
3.7 错误的缓冲区大小

18.png
  1. location / {
  2.     # Too small buffers
  3.     proxy_buffer_size 1k;
  4.     proxy_buffers 4 1k;
  5.    
  6.     # Inconsistent sizes
  7.     client_body_buffer_size 128k;
  8.     client_max_body_size 1m;  # Should be larger
  9. }
  10. http {
  11.     # Appropriate buffer sizes
  12.     client_body_buffer_size 128k;
  13.     client_max_body_size 10m;
  14.     client_header_buffer_size 1k;
  15.     large_client_header_buffers 4 8k;
  16. }
  17. location / {
  18.     # Proxy buffer configuration
  19.     proxy_buffering on;
  20.     proxy_buffer_size 4k;
  21.     proxy_buffers 8 4k;
  22.     proxy_busy_buffers_size 8k;
  23.    
  24.     proxy_pass http://backend;
  25. }
复制代码
3.8 服务器名称哈希桶大小

[code]http {    # Missing hash bucket size with many server names    server {        server_name example.com www.example.com api.example.com cdn.example.com static.example.com;    }        server {        server_name another-very-long-domain-name.com www.another-very-long-domain-name.com;    }}# Nginx may fail to start with error about hash bucket sizehttp {    # Set appropriate hash bucket size    server_names_hash_bucket_size 64;    server_names_hash_max_size 512;        server {        server_name example.com www.example.com api.example.com cdn.example.com static.example.com;        # ... config    }        server {        server_name another-very-long-domain-name.com www.another-very-long-domain-name.com;        # ... config    }}**
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册