nginx常用配置指南

🌟🌌 欢迎来到知识与创意的殿堂 --- 远见阁小民的世界!🚀

🌟🧭 在这里,我们一起探索技术的奥秘,一起在知识的海洋中遨游。

🌟🧭 在这里,每个错误都是成长的阶梯,每条建议都是前进的动力。

🌟🧭 在这里,我们一起成长,一起进步,让我们在知识的世界里畅游无阻,共同创造一个充满智慧和创新的明天。

🌟📚 点击关注,加入我们的技术探索之旅吧!❤️📖✨

✨博客主页:远见阁小民的主页

📕本文专栏:后端专栏

📕其他专栏:AI专栏 Python专栏 其他专栏 白帽学徒笔记 Linux专栏

前言

Nginx作为一种高性能的HTTP和反向代理服务器,以其高效的处理能力和灵活的配置选项而广受欢迎。

为了帮助读者快速上手并掌握Nginx的配置技巧,我在闲暇之余简单做了一下整理,本文以实战为目的编写并介绍了Nginx的常用配置,涵盖从基本设置到高级应用的各个方面。

无论是初学者还是有经验的开发者,都可以通过文章迅速了解并应用Nginx的配置要点,为实际工作需求提供有效的参考和指导。

1 示例①:配置前后端[不带域名证书]

bash 复制代码
worker_processes auto;  # 自动调整为最佳进程数

events {
    worker_connections 1024;
    use epoll;  # Linux系统推荐使用epoll
}

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

    sendfile        on;
    tcp_nopush      on;  # 减少网络延迟
    tcp_nodelay     on;  # 减少网络延迟

    keepalive_timeout  65;
    keepalive_requests 100;  # 每个keepalive连接允许的请求数

    gzip on;  # 开启gzip压缩
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_proxied any;
    gzip_min_length 10240;  # 只压缩大于10KB的响应

    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

    server {
        listen       80;
        server_name  192.168.1.21;

        location / {
            root   /usr/share/nginx/html;
            try_files $uri $uri/ /index.html;
            index  index.html index.htm;
        }

        location /dev-api/ {
            client_max_body_size 10m;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://192.168.1.21:8080/;
            proxy_read_timeout 90;  # 设置代理超时时间
            proxy_connect_timeout 90;  # 设置连接超时时间
            proxy_redirect off;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;  # 修正根目录
        }
    }
}

2 示例②:配置前后端[带域名证书]

bash 复制代码
worker_processes auto;  # 自动调整为最佳进程数

events {
    worker_connections 1024;
    use epoll;  # 在Linux上推荐使用epoll
}

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

    sendfile        on;
    tcp_nopush      on;  # 减少网络延迟
    tcp_nodelay     on;  # 减少网络延迟

    keepalive_timeout  65;
    keepalive_requests 100;  # 每个keepalive连接允许的请求数

    gzip on;  # 开启gzip压缩
    gzip_min_length 10240;  # 只压缩大于10KB的响应
    gzip_types text/plain text/css application/json application/javascript application/xml;
    gzip_proxied any;
    gzip_comp_level 6;  # 设置gzip压缩等级

    server {
        listen       80;
        server_name  63.24.10.11;
        rewrite ^(.*)$ https://$host$1 permanent;
    }

    server {
        listen 443 ssl;
        server_name visit.test.com;

        client_max_body_size 100m;

        ssl_certificate      /etc/nginx/cert/visit.test.com_bundle.crt;
        ssl_certificate_key  /etc/nginx/cert/visit.test.com.key;
        ssl_session_cache    shared:SSL:10m;  # 增加缓存大小
        ssl_session_timeout  10m;
        ssl_protocols TLSv1.2 TLSv1.3;  # 使用更安全的协议版本
        ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';  # 更安全的加密套件
        ssl_prefer_server_ciphers on;

        location / {
            root   /usr/share/nginx/html;
            try_files $uri $uri/ /index.html;
            index  index.html index.htm;
            if ($request_uri = /favicon.ico) {
                return 204;
            }
            expires 1d;
            add_header Cache-Control "public, must-revalidate, proxy-revalidate";
        }

        location /prod-api/ {
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-NginX-Proxy true;
            proxy_pass http://63.24.10.11:8080/;
            proxy_redirect default;
            proxy_connect_timeout 500;
            proxy_read_timeout 1000;
            proxy_send_timeout 1000;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root  /usr/share/nginx/html;  # 修正根目录
        }
    }
}

3 示例③:配置前后端[带域名证书和websocket]

bash 复制代码
worker_processes auto;

events {
    worker_connections 1024;
    use epoll;  # 在Linux上推荐使用epoll
}

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

    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;

    keepalive_timeout  65;
    keepalive_requests 100;

    gzip on;
    gzip_min_length 10240;
    gzip_types text/plain text/css application/json application/javascript application/xml;
    gzip_proxied any;
    gzip_comp_level 6;

    server {
        listen 80;
        server_name example.com;  # 将example.com替换为实际域名
        rewrite ^(.*)$ https://$host$1 permanent;
    }

    server {
        listen 443 ssl;
        server_name secure.example.com;  # 将secure.example.com替换为实际域名

        ssl_certificate      /etc/nginx/cert/secure.example.com_bundle.crt;
        ssl_certificate_key  /etc/nginx/cert/secure.example.com.key;
        ssl_session_cache    shared:SSL:10m;
        ssl_session_timeout  10m;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
        ssl_prefer_server_ciphers on;

        # 增加最大上传大小
        client_max_body_size 20000M;

        location / {
            proxy_pass http://192.168.1.100;  # 将192.168.1.100替换为实际后端服务器地址
            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;
        }

        location /images/ {
            proxy_pass http://192.168.1.100:9300/statics/;  # 将192.168.1.100替换为实际后端服务器地址
            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;
        }

        location /ws {
            proxy_pass http://192.168.1.100:9302;  # 将192.168.1.100替换为实际WebSocket后端服务器地址
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            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;
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /usr/share/nginx/html;  # 修正根目录
        }
    }
}

4 示例③:配置前后端[额外再挂一个ui静态页访问]

bash 复制代码
worker_processes auto;  # 自动调整为最佳进程数

events {
    worker_connections 1024;
    use epoll;  # 在Linux上推荐使用epoll
}

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

    sendfile        on;
    tcp_nopush      on;  # 减少网络延迟
    tcp_nodelay     on;  # 减少网络延迟

    keepalive_timeout  65;
    keepalive_requests 100;  # 每个keepalive连接允许的请求数

    gzip on;  # 开启gzip压缩
    gzip_min_length 10240;  # 只压缩大于10KB的响应
    gzip_types text/plain text/css application/json application/javascript application/xml;
    gzip_proxied any;
    gzip_comp_level 6;  # 设置gzip压缩等级

    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

    server {
        listen       80;
        server_name  192.168.1.16;  # 替换为你的实际域名或IP地址

        location / {
            root   /usr/share/nginx/html/webui;
            try_files $uri $uri/ /index.html;
            index  index.html index.htm;
            expires 1d;
            add_header Cache-Control "public, must-revalidate, proxy-revalidate";
        }

        location /ui {
            alias /usr/share/nginx/html/fileui;
            try_files $uri $uri/ =404;
            expires 1d;
            add_header Cache-Control "public, must-revalidate, proxy-revalidate";
        }

        location /prod-api/ {
            client_max_body_size 100m;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://192.168.1.16:8080/;
            proxy_read_timeout 90;  # 设置代理超时时间
            proxy_connect_timeout 90;  # 设置连接超时时间
            proxy_redirect off;
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /usr/share/nginx/html;  # 修正根目录
        }
    }
}

5 其他示例参考

5.1 反向代理配置

bash 复制代码
# 反向代理配置
server {
    listen 80;  # 监听80端口
    server_name example.com;  # 服务器域名

    location / {
        proxy_pass http://backend_server;  # 将请求转发到后端服务器
        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;  # 设置X-Forwarded-For头信息
        proxy_set_header X-Forwarded-Proto $scheme;  # 设置X-Forwarded-Proto头信息
    }
}

5.2 负载均衡配置

bash 复制代码
# 负载均衡配置
upstream backend {
    server backend1.example.com;  # 后端服务器1
    server backend2.example.com;  # 后端服务器2
}

server {
    listen 80;  # 监听80端口
    server_name example.com;  # 服务器域名

    location / {
        proxy_pass http://backend;  # 将请求转发到负载均衡的后端服务器
        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;  # 设置X-Forwarded-For头信息
        proxy_set_header X-Forwarded-Proto $scheme;  # 设置X-Forwarded-Proto头信息
    }
}

5.3 基于IP地址的访问控制

bash 复制代码
# 基于IP地址的访问控制
server {
    listen 80;
    server_name example.com;

    location / {
        allow 192.168.1.0/24;  # 允许特定IP地址段访问
        deny all;  # 拒绝其他所有IP地址的访问
        root /var/www/html;
        index index.html;
    }
}

5.4 基于用户认证的访问控制

bash 复制代码
# 基于用户认证的访问控制
server {
    listen 80;
    server_name example.com;

    location / {
        auth_basic "Restricted Access";  # 设置基本认证提示信息
        auth_basic_user_file /etc/nginx/.htpasswd;  # 指定密码文件
        root /var/www/html;
        index index.html;
    }
}

生成.htpasswd文件的方法👇

bash 复制代码
# 使用htpasswd工具生成密码文件
htpasswd -c /etc/nginx/.htpasswd username

5.5 URL重写规则

bash 复制代码
# URL重写规则
server {
    listen 80;
    server_name example.com;

    location / {
        rewrite ^/old-path/(.*)$ /new-path/$1 permanent;  # 将旧路径重定向到新路径
        root /var/www/html;
        index index.html;
    }
}

5.6 配置缓存

bash 复制代码
# 配置缓存
server {
    listen 80;
    server_name example.com;

    location / {
        root /var/www/html;
        index index.html;
    }

    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;  # 设置缓存过期时间为30天
        add_header Cache-Control "public, must-revalidate, proxy-revalidate";
    }
}

5.7 配置访问日志和错误日志

bash 复制代码
# 配置访问日志和错误日志
server {
    listen 80;
    server_name example.com;

    access_log /var/log/nginx/access.log main;
    error_log /var/log/nginx/error.log warn;

    location / {
        root /var/www/html;
        index index.html;
    }
}

5.8 配置限制请求速率

bash 复制代码
# 配置限制请求速率
http {
    include mime.types;
    default_type application/octet-stream;

    # 定义一个名为"one"的限速区域,大小为10MB
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

    server {
        listen 80;
        server_name example.com;

        location / {
            limit_req zone=one burst=5 nodelay;  # 应用限速规则,每秒1次请求,允许突发5次请求
            root /var/www/html;
            index index.html;
        }
    }
}

5.9 配置文件上传

bash 复制代码
# 配置文件上传
server {
    listen 80;
    server_name example.com;

    client_max_body_size 50m;  # 设置最大上传文件大小为50MB

    location / {
        root /var/www/html;
        index index.html;
    }
}

5.10 配置连接超时

bash 复制代码
# 配置连接超时
server {
    listen 80;
    server_name example.com;

    client_body_timeout 12;  # 设置客户端请求体超时时间为12秒
    client_header_timeout 12;  # 设置客户端请求头超时时间为12秒
    keepalive_timeout 15;  # 设置keepalive超时时间为15秒
    send_timeout 10;  # 设置发送响应超时时间为10秒

    location / {
        root /var/www/html;
        index index.html;
    }
}
相关推荐
大霞上仙12 分钟前
Ubuntu系统电脑没有WiFi适配器
linux·运维·电脑
Karoku0661 小时前
【企业级分布式系统】Zabbix监控系统与部署安装
运维·服务器·数据库·redis·mysql·zabbix
为什么这亚子1 小时前
九、Go语言快速入门之map
运维·开发语言·后端·算法·云原生·golang·云计算
布值倒区什么name1 小时前
bug日常记录responded with a status of 413 (Request Entity Too Large)
运维·服务器·bug
。puppy2 小时前
HCIP--3实验- 链路聚合,VLAN间通讯,Super VLAN,MSTP,VRRPip配置,OSPF(静态路由,环回,缺省,空接口),NAT
运维·服务器
颇有几分姿色2 小时前
深入理解 Linux 内存管理:free 命令详解
linux·运维·服务器
光芒再现dev2 小时前
已解决,部署GPTSoVITS报错‘AsyncRequest‘ object has no attribute ‘_json_response_data‘
运维·python·gpt·语言模型·自然语言处理
AndyFrank3 小时前
mac crontab 不能使用问题简记
linux·运维·macos
成都古河云4 小时前
智慧场馆:安全、节能与智能化管理的未来
大数据·运维·人工智能·安全·智慧城市
算法与编程之美4 小时前
文件的写入与读取
linux·运维·服务器