Nginx配置详解

Nginx配置详解

Nginx配置详解

Nginx的配置文件通常位于 /etc/nginx/nginx.conf 或者 /usr/local/nginx/conf/nginx.conf,其配置文件结构清晰且层次分明,主要由全局块、events块、http块(含多个server块)以及其他可选的mail块组成。以下是对主要部分的配置详解:

  1. 全局块

    # 全局块
    user nginx;           # Nginx worker进程的用户和组,默认为nobody
    worker_processes auto; # 工作进程数量,根据CPU核心数自动设置
    error_log /var/log/nginx/error.log; # 错误日志文件
    pid /run/nginx.pid;   # Nginx主进程PID文件
    
    
  2. events块

    events {
        use epoll;      # 事件驱动模型,epoll在Linux系统上高效
        worker_connections 1024; # 每个工作进程允许的最大连接数
    }
    
    
  3. http块

    http {
        include /etc/nginx/mime.types;  # MIME类型映射文件
        default_type application/octet-stream; # 默认MIME类型
    
        log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                        '$status $body_bytes_sent "$http_referer" '
                        '"$http_user_agent" "$http_x_forwarded_for"'; # 日志格式定义
    
        access_log /var/log/nginx/access.log main; # 访问日志文件及格式
        sendfile on;  # 提高文件传输效率
        tcp_nopush on; # 减少网络报文段的产生
        tcp_nodelay on; # 减少延迟
        # Server块配置(虚拟主机)
    
        server {
            listen 80;         # 监听端口
            server_name example.com www.example.com; # 域名或IP地址
    
            # 根目录配置
            root  /root/usr/web;
            index index.html index.htm;
            # location块配置(路由规则)
            location / {
                try_files $uri $uri/ /index.html;
            }
        }
        
        # 可以有多个server块配置,服务于不同的域名或端口
        server {
            ...
        }
    }
    
    
  4. mail块
    如果需要配置邮件服务器,可以在此添加 mail 块,不过这不是Nginx常用的功能。

Nginx配置Gzip压缩

其中:gzip 相关前缀的代表开启gzip压缩,使得前端页面访问更快

server {
        gzip on;
        gzip_min_length 2k;
        gzip_buffers 4 16k;
        gzip_http_version 1.0;
        gzip_comp_level 2;
        gzip_types text/plain application/javascript text/css application/xml;
        gzip_vary on;
        server_name node.hanyuanhun.cn;
        listen 80;
        location / {
                root  /usr/local/soft/node/dist;
                #index index.html;
                try_files $uri $uri/ /index.html;
         }
     }


配置Nginx代理端口转发

在Nginx中实现端口转发(代理)通常使用proxy_pass指令。下面是一个基本的例子,展示了如何配置Nginx将特定端口的请求转发到另一个服务器或端口:

场景举例:假设你想让所有访问到http://yourdomain.com:8080的请求都被转发到内部服务器的http://localhost:8000

Nginx配置示例

server {
    listen 8080;  # 监听外部端口8080
    server_name yourdomain.com;  # 可选,如果需要基于域名转发

    location / {  # 处理所有请求
        proxy_pass http://localhost:8000;  # 将请求转发到内部服务器的8000端口
        proxy_set_header Host $host;  # 保持原始Host头信息
        proxy_set_header X-Real-IP $remote_addr;  # 传递真实客户端IP
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  # 支持代理链
        # 其他可选的proxy指令,如proxy_read_timeout、proxy_redirect等
    }
   #或者路径匹配
    location /api {
            proxy_pass http://localhost:8000;
            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配置负载均衡

在Nginx中配置负载均衡,可以通过upstream模块来实现,将来自客户端的请求分发到后端的一组服务器上。以下是一个基本的负载均衡配置示例:

http {
    upstream backend_servers {
        # 负载均衡策略配置
        # 轮询(默认)
        server backend1.example.com;
        server backend2.example.com;
        
        # 权重轮询
        server backend1.example.com weight=3;
        server backend2.example.com;

        # 最少连接数
        least_conn;

        # IP哈希
        ip_hash;

        # 健康检查配置
        server backend1.example.com max_fails=3 fail_timeout=30s;
    }

    server {
        listen 80;  # 监听的端口,也可以是443(HTTPS)

        # 域名匹配
        server_name example.com;

        # 请求转发到upstream配置的后端服务器组
        location / {
            proxy_pass http://backend_servers;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}

配置详解:

  1. upstream backend_servers:定义一个名为backend_servers的上游服务器组,用于存放后端服务器列表。

  2. server指令:列出后端服务器地址,每个地址代表一个后端服务器。

    • 轮询(默认):如果没有指定权重或特殊策略,Nginx会均匀地将请求分配给所有后端服务器。
      Nginx支持轮询模式默认、ip 哈希  、 url 哈希、weight(指定轮询几率)、fair(根据响应时间)
    • 权重轮询:通过weight参数为每个服务器分配一个权重,权重高的服务器将接收更多请求。
    • 最少连接数:使用least_conn策略,Nginx将请求分配给当前连接数最少的服务器。
    • IP哈希:使用ip_hash策略,Nginx根据客户端IP地址的哈希值来选择服务器,实现会话黏连(sticky session)效果。
    • 健康检查:通过max_failsfail_timeout参数进行服务器健康检查,如果服务器在fail_timeout时间内连续max_fails次检查失败,则认为该服务器不可用。

Nginx配置https

server {
        server_name node.hanyuanhun.cn;
        listen 443 ssl;
        #证书公钥
        ssl_certificate /usr/local/xxx.xxx.cn.crt;
        #证书私钥
        ssl_certificate_key /usr/local/xxx.xxx.cn.key;
        ssl_session_timeout  5m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers AESGCM:ALL:!DH:!EXPORT:!RC4:+HIGH:!MEDIUM:!LOW:!aNULL:!eNULL;
        ssl_prefer_server_ciphers   on;
        location / {
              #此处更具自己的配置...
          }
  }

#配置将80转到443

server {
    listen       80;
    server_name  www.hanyuanhun.cn  node.hanyuanhun.cn;

    location / {
        rewrite ^(.*)$ https://$host$1 permanent;
    }
}

配置日志生成格式以及归档

image.png
image.png

http {
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
  #配置日志分割方式,按日期分割
     map $time_iso8601 $logdate {
        '~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
         default 'date-not-found';
      }
     access_log /usr/local/nginx/logs/access_$logdate.log main;
     sendfile        on;
}

配置IP黑名单

http {
	include       mime.types;
	default_type  application/octet-stream;

	#IP黑名单 防止频繁恶意通过IP访问盗刷
	deny 90.151.171.108;
	deny 123.56.155.157;
	deny 122.116.224.61;
}

原文链接 https://www.hanyuanhun.cn | https://node.hanyuanhun.cn

posted @   汉源魂  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示