优秀的编程知识分享平台

网站首页 > 技术文章 正文

玩转Nginx:从安装到高级使用实战指南

nanyue 2025-09-24 01:05:00 技术文章 1 ℃

玩转Nginx:从安装到高级使用实战指南

Nginx 是一款高性能的 HTTP 和反向代理服务器,以高并发、低内存占用和灵活配置著称,是现代 Web 架构的核心组件。
本文将带你从零开始,快速掌握 Nginx 的安装、配置、优化、安全加固以及运维监控,让你既能入门,也能直接应用到生产环境。


一、快速安装与启动速查表

# Ubuntu/Debian
sudo apt update && sudo apt install nginx -y
sudo systemctl enable --now nginx

# CentOS/RHEL
sudo yum install epel-release -y && sudo yum install nginx -y
sudo systemctl enable --now nginx

# 测试访问
curl http://127.0.0.1

二、安装与启动(详细版)

1. Linux 通过包管理器安装(推荐)

Ubuntu/Debian系统:

# 更新软件包列表
sudo apt update

# 安装Nginx
sudo apt install nginx

# 启动Nginx
sudo systemctl start nginx

# 设置开机自启
sudo systemctl enable nginx

CentOS/RHEL系统:

# 安装EPEL仓库(CentOS/RHEL需要)
sudo yum install epel-release

# 更新并安装Nginx
sudo yum update
sudo yum install nginx

# 启动Nginx
sudo systemctl start nginx

# 设置开机自启
sudo systemctl enable nginx

2. 源码编译安装(自定义需求)

# 安装编译依赖
sudo yum install -y gcc pcre-devel openssl-devel zlib-devel
# 或Ubuntu系统
sudo apt install -y build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev

# 下载源码(以Nginx 1.25.3为例)
wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar -xzvf nginx-1.25.3.tar.gz
cd nginx-1.25.3

# 配置编译选项(可自定义路径和模块)
./configure --prefix=/usr/local/nginx --with-http_ssl_module

# 编译并安装
make
sudo make install

# 启动Nginx
sudo /usr/local/nginx/sbin/nginx

3. Windows 安装

  1. 从官网下载Windows版本的Nginx压缩包(如nginx-1.25.3.zip)
  2. 解压到任意目录(如C:\nginx)
  3. 启动方式:
  • 命令行:cd C:\nginx然后start nginx
  • 直接双击nginx.exe
  1. 验证:浏览器访问http://localhost,看到"Welcome to nginx!"即成功

三、基本配置与常用命令

1. 常用命令

nginx -v          # 查看版本
nginx -t          # 测试配置文件
nginx             # 启动
nginx -s reload   # 重载配置
nginx -s quit     # 优雅停止

2. 防火墙放行

firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --reload

四、核心功能配置(实战优化)

1. 静态资源服务

server {
    listen 80;
    server_name localhost;

    location / {
        root /opt/static;
        index index.html;
    }

    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        root /opt/static;
        expires 30d;
    }
}

2. 反向代理(加超时与错误处理)

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1: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_connect_timeout 5s;
        proxy_send_timeout 10s;
        proxy_read_timeout 30s;

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /usr/share/nginx/html;
        }
    }
}

3. 负载均衡(加健康检查)

upstream backend {
    least_conn;  # 最少连接策略
    server 192.168.1.101:8080 max_fails=3 fail_timeout=30s;
    server 192.168.1.102:8080 max_fails=3 fail_timeout=30s;
}

server {
    listen 80;
    server_name lb.example.com;

    location / {
        proxy_pass http://backend;
    }
}

4. 缓存加速

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;

server {
    listen 80;
    server_name cache.example.com;

    location / {
        proxy_cache my_cache;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_pass http://backend;
    }
}

5. HTTPS 配置

server {
    listen       443 ssl;
    server_name  secure.example.com;
    
    ssl_certificate      /path/to/cert.pem;
    ssl_certificate_key  /path/to/key.pem;
    
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;
    
    ssl_ciphers  HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers  on;
    
    location / {
        root   html;
        index  index.html index.htm;
    }
}

# HTTP重定向到HTTPS
server {
    listen       80;
    server_name  secure.example.com;
    return 301 https://$host$request_uri;
}

五、安全加固(扩展版)

server_tokens off;  # 隐藏版本号
client_max_body_size 10m;  # 限制上传大小

# 限制 HTTP 方法
if ($request_method !~ ^(GET|HEAD|POST)$) {
    return 405;
}

# 防爬虫 / 防 CC 攻击
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=1r/s;
limit_req zone=req_limit burst=5 nodelay;

if ($http_user_agent ~* (scrapy|curl|wget|python) ) {
    return 403;
}

# 安全响应头
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'";

六、性能优化(生产建议)

events {
    worker_connections 10240;
    use epoll;
    multi_accept on;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    gzip on;
    gzip_types text/plain text/css application/json application/javascript;
    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid 30s;
}

七、监控与运维

1. Nginx 运行状态

location /nginx_status {
    stub_status on;
    allow 127.0.0.1;
    deny all;
}

2. 搭配 Prometheus Exporter

  • nginx-prometheus-exporter 提供监控指标
  • 可结合 Grafana 做可视化

3. 日志分析

  • 实时分析:tail -f logs/access.log
  • 图形化分析:goaccess access.log -o report.html --log-format=COMBINED

八、最佳实践清单

  • 性能:启用 gzip、HTTP/2、缓存
  • 安全:开启限流、防爬虫、TLS1.3
  • 运维:systemd 管理、日志分割、Prometheus 监控
  • 高可用:负载均衡 + 健康检查
  • 调试:nginx -t 检查配置,错误日志实时查看

结语

通过本文,你可以快速从零部署 Nginx,并用上生产环境中最常用的优化、安全和监控配置。
在实际场景中,建议根据业务流量和安全需求持续调整参数,Nginx 的强大之处就在于它的高度可定制性。

最近发表
标签列表