Nginx的使用

Nginx 是一款高性能的 HTTP 和反向代理服务器,也可作为负载均衡器、邮件代理和 HTTP 缓存使用。它以轻量级、高并发、低内存消耗等特点被广泛应用。以下是 Nginx 的核心使用知识:

一、Nginx 基本操作

1. 安装 Nginx
  • CentOS/RHEL
sudo yum install nginx  # CentOS 7
# 或
sudo dnf install nginx  # CentOS 8+/RHEL 8+
  • Ubuntu/Debian
sudo apt update
sudo apt install nginx
  • Windows/macOS:可通过官网下载安装包,或使用包管理工具(如 Homebrew for macOS)。
2. 常用命令
# 启动 Nginx
sudo systemctl start nginx  # 系统服务方式
# 或
nginx                       # 直接运行

# 停止 Nginx
sudo systemctl stop nginx
# 或
nginx -s stop               # 快速停止
nginx -s quit               # 优雅停止(处理完当前请求)

# 重启 Nginx(配置文件修改后需执行)
sudo systemctl restart nginx
# 或
nginx -s reload             # 平滑重启(不中断服务)

# 查看状态
sudo systemctl status nginx

# 验证配置文件是否正确
nginx -t

二、核心配置文件结构

Nginx 主配置文件默认路径:

  • Ubuntu/Debian:/etc/nginx/nginx.conf
  • CentOS/RHEL:/etc/nginx/nginx.conf
  • Windows:安装目录/conf/nginx.conf

配置文件基本结构:

# 全局块:配置影响 Nginx 整体运行的参数
user nginx;                  # 运行 Nginx 的用户
worker_processes auto;       # 工作进程数(建议设为 CPU 核心数)
error_log /var/log/nginx/error.log;  # 错误日志路径
pid /run/nginx.pid;          # 进程 PID 文件

# 事件块:配置网络连接相关参数
events {
    worker_connections 1024;  # 每个工作进程的最大连接数
    use epoll;                # 高效事件驱动模型(Linux 推荐)
}

# HTTP 块:配置 HTTP 服务器的核心参数
http {
    include /etc/nginx/mime.types;  # 引入 MIME 类型映射
    default_type application/octet-stream;

    # 日志格式定义
    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;            # 配合 sendfile 使用,提高网络效率
    tcp_nodelay on;
    keepalive_timeout 65;     # 长连接超时时间
    types_hash_max_size 2048;

    # 引入虚拟主机配置(推荐将站点配置分离到单独文件)
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

三、虚拟主机配置(多站点部署)

通过虚拟主机可在一台服务器上部署多个网站,常用基于域名的虚拟主机配置:

  1. 在 /etc/nginx/conf.d/ 目录下创建站点配置文件(如 example.com.conf):
    server {
        listen 80;                   # 监听端口(HTTP 默认 80)
        server_name example.com www.example.com;  # 绑定的域名
    
        root /var/www/example.com;   # 网站根目录
        index index.html index.htm;  # 默认首页
    
        # 访问日志(可选)
        access_log /var/log/nginx/example.com.access.log main;
        error_log /var/log/nginx/example.com.error.log;
    
        # location 块:匹配 URL 路径并配置处理规则
        location / {
            try_files $uri $uri/ =404;  # 尝试访问文件,不存在则返回 404
        }
    
        # 处理 PHP 脚本(若需运行 PHP)
        location ~ \.php$ {
            fastcgi_pass 127.0.0.1:9000;  # 转发到 PHP-FPM 进程
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
    }
  2. 创建网站目录并添加测试页面:
    sudo mkdir -p /var/www/example.com
    echo "<h1>Welcome to example.com</h1>" | sudo tee /var/www/example.com/index.html
  3. 验证配置并重启 Nginx:
nginx -t
sudo systemctl restart nginx

四、反向代理配置

Nginx 作为反向代理,可将客户端请求转发到后端服务器(如 Node.js、Tomcat 等),隐藏后端服务细节并提高安全性。

示例:将 api.example.com 的请求转发到本地 3000 端口的 Node.js 服务:

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

    location / {
        proxy_pass http://127.0.0.1:3000;  # 后端服务地址
        proxy_set_header Host $host;       # 传递主机名
        proxy_set_header X-Real-IP $remote_addr;  # 传递客户端真实 IP
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

五、SSL 证书配置(HTTPS)

  1. 准备 SSL 证书(如从 Let's Encrypt 或商业 CA 申请),获得证书文件(如 cert.pem)和私钥文件(如 key.pem)。

  2. 配置 HTTPS 站点(修改或新增 server 块):

    server {
        listen 443 ssl;              # 监听 HTTPS 默认端口 443
        server_name example.com;
    
        # SSL 证书路径
        ssl_certificate /etc/nginx/ssl/cert.pem;
        ssl_certificate_key /etc/nginx/ssl/key.pem;
    
        # 优化 SSL 配置(增强安全性)
        ssl_protocols TLSv1.2 TLSv1.3;  # 支持的 TLS 版本
        ssl_ciphers HIGH:!aNULL:!MD5;   # 加密套件
        ssl_prefer_server_ciphers on;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;
    
        # 网站根目录和其他配置(同 HTTP)
        root /var/www/example.com;
        index index.html;
    
        location / {
            try_files $uri $uri/ =404;
        }
    }
    
    # 可选:将 HTTP 请求强制跳转至 HTTPS
    server {
        listen 80;
        server_name example.com;
        return 301 https://$host$request_uri;
    }

    六、负载均衡配置

Nginx 可作为负载均衡器,将请求分发到多个后端服务器,提高服务可用性和并发能力。

示例:

http {
    # 定义后端服务器组(名称自定义,如 backend_servers)
    upstream backend_servers {
        server 192.168.1.100:8080;  # 后端服务器 1
        server 192.168.1.101:8080;  # 后端服务器 2
        # 可选:设置权重(weight)、健康检查(max_fails、fail_timeout)等
        # server 192.168.1.102:8080 weight=2 max_fails=3 fail_timeout=30s;
    }

    # 负载均衡代理配置
    server {
        listen 80;
        server_name loadbalance.example.com;

        location / {
            proxy_pass http://backend_servers;  # 转发到定义的服务器组
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
}

负载均衡策略(默认是轮询):

  • weight:权重(值越高,分配的请求越多);
  • ip_hash:按客户端 IP 哈希分配,确保同一客户端请求固定服务器;
  • least_conn:优先分配到连接数最少的服务器。

七、常见问题与调试

  1. 配置错误:使用 nginx -t 检查配置文件语法,错误信息会显示具体位置。
  2. 端口占用:若启动失败,可能是 80/443 端口被占用,使用 netstat -tulpn | grep 80 查看占用进程并关闭。
  3. 日志排查:错误日志(/var/log/nginx/error.log)记录了详细的错误原因,是调试的主要依据。
  4. 权限问题:确保 Nginx 进程对网站目录和文件有读取权限,可通过 chmod 或 chown 调整。

通过以上配置,Nginx 可满足大多数 Web 服务场景需求。实际使用中,可根据业务复杂度进一步优化配置(如缓存、压缩、防盗链等)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值