当前位置: 代码网 > it编程>数据库>Redis > Nginx 基本使用和高级用法示例详解

Nginx 基本使用和高级用法示例详解

2025年10月21日 Redis 我要评论
nginx 基本使用和高级用法详解一、nginx 简介nginx 是一个高性能的 http 和反向代理服务器,具有占用内存少、并发能力强等特点,广泛应用于 web 服务、负载均衡、静态资源处理和反向代

nginx 基本使用和高级用法详解

一、nginx 简介

nginx 是一个高性能的 http 和反向代理服务器,具有占用内存少、并发能力强等特点,广泛应用于 web 服务、负载均衡、静态资源处理和反向代理等场景。

二、基本安装与使用

1. 安装 nginx

ubuntu/debian
sudo apt update
sudo apt install nginx
centos/rhel
sudo yum install nginx
# 或
sudo dnf install nginx

2. 基本操作命令

# 启动
sudo systemctl start nginx
# 停止
sudo systemctl stop nginx
# 重启
sudo systemctl restart nginx
# 重新加载配置(不中断服务)
sudo systemctl reload nginx
# 查看状态
sudo systemctl status nginx
# 开机自启
sudo systemctl enable nginx

三、配置文件结构

1. 主要配置文件目录结构

/etc/nginx/
├── nginx.conf              # 主配置文件
├── conf.d/                 # 额外配置文件目录
├── sites-available/        # 可用站点配置文件
└── sites-enabled/          # 已启用站点配置文件(软链接指向 sites-available)

2. 基本配置示例(/etc/nginx/nginx.conf)

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}
http {
    include /etc/nginx/mime.types;
    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;
    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/sites-available/example.com
server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example.com;
    index index.html index.htm;
    location / {
        try_files $uri $uri/ =404;
    }
    # 静态资源缓存优化
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 1y;
        add_header cache-control "public, immutable";
    }
}

2. 启用站点

# 创建软链接启用站点
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
# 测试配置是否正确
sudo nginx -t
# 重新加载配置
sudo systemctl reload nginx

五、高级配置技巧

1. 反向代理配置

server {
    listen 80;
    server_name api.example.com;
    location / {
        proxy_pass http://localhost:3000;
        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 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
        # 缓冲设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
    }
}

2. 负载均衡

upstream backend {
    server backend1.example.com weight=3;
    server backend2.example.com;
    server backend3.example.com;
    server backup.example.com backup;
}
server {
    listen 80;
    server_name app.example.com;
    location / {
        proxy_pass http://backend;
        proxy_set_header host $host;
        proxy_set_header x-real-ip $remote_addr;
    }
}

3. ssl/tls 配置

server {
    listen 443 ssl http2;
    server_name example.com;
    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    # ssl 安全设置
    ssl_protocols tlsv1.2 tlsv1.3;
    ssl_ciphers ecdhe-rsa-aes128-gcm-sha256:ecdhe-rsa-aes256-gcm-sha384;
    ssl_prefer_server_ciphers off;
    # hsts 强制 https
    add_header strict-transport-security "max-age=63072000" always;
    root /var/www/example.com;
    index index.html;
}

4. 缓存配置

代理缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g 
                 inactive=60m use_temp_path=off;
server {
    location / {
        proxy_cache my_cache;
        proxy_pass http://backend;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        add_header x-cache-status $upstream_cache_status;
    }
}
静态资源缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
    expires 1y;
    add_header cache-control "public, immutable";
}

5. 安全配置

# 隐藏版本号
server_tokens off;
# 安全响应头
add_header x-frame-options "sameorigin" always;
add_header x-xss-protection "1; mode=block" always;
add_header x-content-type-options "nosniff" always;
add_header referrer-policy "no-referrer-when-downgrade" always;
add_header content-security-policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
# 上传大小限制
client_max_body_size 10m;
# 限制非法请求方法
if ($request_method !~ ^(get|post|head)$) {
    return 405;
}

6. 限流配置

# 定义限流区域
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=2r/m;
server {
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        proxy_pass http://backend;
    }
    location /login {
        limit_req zone=login burst=5;
        proxy_pass http://backend;
    }
}

7. url 重写和重定向

server {
    # 强制跳转 https
    if ($scheme = http) {
        return 301 https://$server_name$request_uri;
    }
    # 路径重定向
    location /old-path {
        return 301 /new-path;
    }
    # 去除 .html 扩展名
    location / {
        try_files $uri $uri.html $uri/ =404;
    }
    # restful url 重写
    location /api/v1/users {
        rewrite ^/api/v1/users/(.*)$ /api/v1/users?id=$1 last;
    }
}

8. gzip 压缩

gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied any;
gzip_comp_level 6;
gzip_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/json
    application/javascript
    application/xml+rss
    application/atom+xml
    image/svg+xml;

六、性能优化配置

1. 连接优化

events {
    worker_connections 4096;
    use epoll;
    multi_accept on;
}
http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    keepalive_requests 1000;
    # 文件描述符缓存
    open_file_cache max=200000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
}

2. 工作进程优化

worker_processes auto;
worker_cpu_affinity auto;
# 提高文件描述符限制
worker_rlimit_nofile 65535;

七、日志配置

1. 自定义日志格式

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for" '
                'rt=$request_time uct="$upstream_connect_time" '
                'uht="$upstream_header_time" urt="$upstream_response_time"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;

2. 日志分割脚本(rotate_nginx_logs.sh)

#!/bin/bash
# rotate_nginx_logs.sh
log_dir="/var/log/nginx"
date=$(date -d "yesterday" +%y-%m-%d)
mv $log_dir/access.log $log_dir/access.$date.log
mv $log_dir/error.log $log_dir/error.$date.log
# 通知 nginx 重新打开日志文件
kill -usr1 $(cat /var/run/nginx.pid)
# 压缩7天前的日志
find $log_dir -name "*.log" -mtime +7 -exec gzip {} \;

提示:可配合 cron 定时执行日志轮转。

八、监控和调试

1. 状态页面配置

server {
    listen 8080;
    server_name localhost;
    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }
}

访问 http://localhost:8080/nginx_status 可查看连接状态。

2. 调试常用命令

# 测试配置语法
sudo nginx -t
# 打印完整配置(含 include)
sudo nginx -t
# 查看 nginx 编译参数和模块
nginx -v
# 实时查看日志
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log
# 压力测试(apache bench)
ab -n 1000 -c 100 http://example.com/

九、docker 中的 nginx

1. dockerfile 示例

from nginx:alpine
copy nginx.conf /etc/nginx/nginx.conf
copy sites/ /etc/nginx/sites-available/
copy html/ /usr/share/nginx/html/
run ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
expose 80 443
cmd ["nginx", "-g", "daemon off;"]

2. docker compose 示例

version: '3.8'
services:
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./sites:/etc/nginx/sites-available
      - ./html:/usr/share/nginx/html
      - ./ssl:/etc/ssl
    networks:
      - webnet
networks:
  webnet:
    driver: bridge

结语

本指南涵盖了 nginx 的 基础安装、虚拟主机、反向代理、负载均衡、ssl 配置、缓存、安全加固、限流、url 重写、gzip 压缩、性能调优、日志管理、监控调试 以及 docker 部署 等核心内容,适用于构建高可用、高性能、安全的 web 服务架构。

建议在生产环境中结合具体业务场景进行配置优化,并定期审查安全策略和性能指标。

到此这篇关于nginx 基本使用和高级用法详解的文章就介绍到这了,更多相关nginx 安装使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

  • Redis批量查询的四种方式详解

    引言在高并发场景下,巧妙地利用缓存批量查询技巧能够显著提高系统性能。在笔者看来,熟练掌握细粒度的缓存使用是每位架构师必备的技能。因此,在本文中,我们将深入探讨 redis 中批量查…

    2025年10月16日 数据库
  • Redis主从+哨兵集群部署详解

    Redis主从+哨兵集群部署详解

    一、 哨兵模式介绍在一主多从的 redis 架构中,从节点可以起到数据冗余备份和读写分离的作用。如果主节点遇到故障导致无法提供服务时,可以采用手动方式将其一个从... [阅读全文]
  • Redis中的配置与优化过程

    Redis中的配置与优化过程

    一、 redis 介绍1. 关系型数据库与非关系型数据库数据库按照数据库的结构可以分为关系型数据库与其他数据库,而这些其他数据库我们将其统称为非关系型数据库。(... [阅读全文]
  • redis的主从模式复制的具体步骤

    redis的主从模式复制的具体步骤

    在分布式系统中,希望使用多个服务器来部署redis,存在以下几种redis的部署方式:1.主从模式 2.主从模式+哨兵模式 3.集群模式主从模式的优点:可以实现... [阅读全文]
  • Nginx分布式部署流程分析

    Nginx分布式部署流程分析

    分布式部署分布式部署也叫集群或机群(多台电脑整合在一起,都运行相同的项目)。nginxnginx是做代理的,且nginx是反向代理。(vpn是 正向代理)jav... [阅读全文]
  • Redis 实现消息队列实际案例

    Redis 实现消息队列实际案例

    一、为什么选择 redis 做消息队列?1.1 redis 消息队列的核心优势轻量级部署:无需单独部署 rabbitmq、kafka 等消息队列服务,可以直接复... [阅读全文]

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com