nginx的基本设置与详细说明

基本设置

1. 基础配置
user nginx;  
# 指定 Nginx 工作进程以 `nginx` 用户运行,提高安全性  
worker_processes auto;  
# 根据 CPU 核心数自动设置工作进程数量,优化性能  
error_log /var/log/nginx/error.log notice;  
# 错误日志路径,记录级别为 `notice`(重要通知信息)  
pid /var/run/nginx.pid;  
# 存储主进程 PID 的文件位置  
events {  
    worker_connections 1024;  
}  
# 每个工作进程的最大并发连接数为 1024  
2. HTTP 模块基础配置
include /etc/nginx/mime.types;  
# 加载 MIME 类型定义文件,正确识别文件类型  
default_type application/octet-stream;  
# 默认 MIME 类型为二进制流(当无法识别文件类型时使用)  
3. 日志增强(安全审计)
log_format security '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for" $request_time $ssl_protocol/$ssl_cipher $upstream_addr $upstream_status';  
# 自定义日志格式 `security`,记录 IP、用户、时间、请求、状态、UA、SSL 协议等安全相关字段  
access_log /var/log/nginx/access.log security;  
# 访问日志使用 `security` 格式,便于安全审计  
4. 性能优化配置
sendfile on;  
# 使用 `sendfile` 内核优化文件传输,减少 CPU 消耗  
tcp_nopush on;  
# 数据包累积到一定大小再发送,提高传输效率  
tcp_nodelay on;  
# 禁用 Nagle 算法,降低延迟  
server_names_hash_bucket_size 128;  
# 服务器名哈希表桶大小,优化域名查找  
server_names_hash_max_size 512;  
# 服务器名哈希表最大大小  
keepalive_timeout 1000;  
# 保持连接的超时时间(1000 秒)  
client_header_timeout 15s;  
# 客户端请求头超时时间(15 秒)  
client_body_timeout 15s;  
# 客户端请求体超时时间(15 秒)  
send_timeout 60s;  
# 响应超时时间(60 秒)  
5. 全局安全加固(影响所有 Server 块)
5.1 隐藏服务器信息
server_tokens off;  
# 隐藏 Nginx 版本号(防止信息泄露)  
add_header Server "";
# 完全移除 `Server` 响应头(进一步隐藏服务器信息)  
5.2 请求限制(防 DDoS/CC 攻击)
limit_conn_zone $binary_remote_addr zone=global_conn:10m;  
# 限制单个 IP 的连接数(分配 10MB 内存存储连接状态)  
limit_req_zone $binary_remote_addr zone=global_req:10m rate=10r/s;  
# 限制单个 IP 的请求速率(10 请求/秒)  
limit_conn global_conn 100;  
# 每个 IP 最大并发连接数(100)  
5.3 安全响应头(防 XSS/点击劫持等)
add_header X-Frame-Options "SAMEORIGIN" always;  
# 防止页面被 iframe 嵌套(点击劫持防护)  
add_header X-Content-Type-Options "nosniff" always;  
# 禁止浏览器 MIME 类型嗅探(防 XSS)  
add_header X-XSS-Protection "1; mode=block" always;  
# 启用 XSS 过滤器并阻止攻击  
add_header Referrer-Policy "strict-origin-when-cross-origin" always;  
# 控制 Referer 头信息(防止敏感信息泄露)  
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https:; img-src 'self' data: https:; style-src 'self' 'unsafe-inline' https:; font-src 'self' https:;" always;  
# 内容安全策略(限制资源加载来源)  
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;  
# 拦截常见后台路径和目录遍历攻击  
5.6 SSL/TLS 安全配置(防中间人攻击)
ssl_protocols TLSv1.2 TLSv1.3;  
# 仅允许 TLS 1.2 和 1.3(禁用旧的不安全协议)  
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';  
# 仅允许强加密套件
ssl_prefer_server_ciphers on;  
# 优先使用服务器端的加密套件  
ssl_session_cache shared:SSL:10m;  
# SSL 会话缓存(提高性能)  
ssl_session_timeout 10m;  
# SSL 会话超时时间(10 分钟)  
ssl_stapling on;  
# 启用 OCSP Stapling(提高 SSL 验证速度)  
ssl_stapling_verify on;  
# 验证 OCSP 响应  
6. 缓存与代理优化
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=nginx-cache:20m max_size=10g inactive=168h use_temp_path=off;  
# 代理缓存路径(最大 10GB,7 天未访问则清理)  
client_body_buffer_size 512k;  
# 客户端请求体缓冲区大小(512KB)  
client_header_buffer_size 4k;  
# 客户端请求头缓冲区大小(4KB)  
client_max_body_size 1024M;  
# 允许的最大客户端请求体大小(1GB)  
large_client_header_buffers 2 8k;  
# 大请求头缓冲区(2 个 8KB)  
proxy_connect_timeout 5s;  
# 代理连接超时(5 秒)  
proxy_send_timeout 120s;  
# 代理发送超时(120 秒)  
proxy_read_timeout 120s;  
# 代理读取超时(120 秒)  
proxy_buffer_size 16k;  
# 代理缓冲区大小(16KB)  
proxy_buffers 4 64k;  
# 代理缓冲区数量与大小(4 个 64KB)  
proxy_busy_buffers_size 128k;  
# 代理繁忙缓冲区大小(128KB)  
proxy_temp_file_write_size 128k;  
# 代理临时文件写入大小(128KB)  
proxy_next_upstream http_502 http_504 http_404 error timeout invalid_header;  
# 当遇到 502/504/404 等错误时,尝试下一个上游服务器  
7. 压缩优化(减少传输大小)
gzip on;  
# 启用 Gzip 压缩  
gzip_static on;  
# 优先使用预压缩文件(`.gz`)  
gzip_min_length 1000;  
# 仅压缩大于 1KB 的文件  
gzip_buffers 4 16k;  
# Gzip 缓冲区(4 个 16KB)  
gzip_comp_level 1;  
# 压缩级别(1-9,1 最快但压缩率低)  
gzip_http_version 1.1;  
# 支持 HTTP/1.1 的压缩  
gzip_vary on;  
# 根据 `Accept-Encoding` 头动态调整压缩  
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;  
# 压缩指定 MIME 类型的文件  
gzip_disable "MSIE [1-6]\.";  
# 禁用旧版 IE 的 Gzip(避免兼容性问题)  
8. 文件缓存优化(减少磁盘 I/O)
open_file_cache max=655350 inactive=20s;  
# 文件描述符缓存(最大 655350 个,20 秒未使用则关闭)  
open_file_cache_valid 30s;  
# 缓存有效性检查周期(30 秒)  
open_file_cache_min_uses 2;  
# 文件至少被访问 2 次才缓存  
open_file_cache_errors on;  
# 缓存文件访问错误信息  
9. 加载额外配置
include /etc/nginx/conf.d/*.conf;  
# 加载 `/etc/nginx/conf.d/` 下的其他配置文件

## 以下内容需要单独加到单个的  /etc/nginx/conf.d/*.conf中含有server 下的有location方法的案例中

5.4 强制 HTTPS(防止降级攻击)
if ($http_x_forwarded_proto != 'https') {  
    return 301 https://$host$request_uri;  
}  
# 如果请求不是 HTTPS,则 301 重定向到 HTTPS  
5.5 敏感路径拦截(防扫描/入侵)
location ~* (\.(env|git|svn|htaccess|bak|swp)|config\.|backup/) {  
    deny all;  
    return 403;  
}  
# 拦截 `.env`、`.git`、`.htaccess` 等敏感文件访问  
location ~* (wp-admin|admin|console|\.\./) {  
    deny all;  
    return 403;  
}

以上是nginx配置每项说明,不可以直接使用,下面是才是正常使用配置。

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

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

    # 安全增强的日志格式(记录更多安全相关字段)
    log_format  security  '$remote_addr - $remote_user [$time_local] '
                          '"$request" $status $body_bytes_sent '
                          '"$http_referer" "$http_user_agent" '
                          '"$http_x_forwarded_for" $request_time '
                          '$ssl_protocol/$ssl_cipher '
                          '$upstream_addr $upstream_status';

    access_log  /var/log/nginx/access.log  security;

    # 基础性能配置
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    server_names_hash_bucket_size 128;
    server_names_hash_max_size 512;
    keepalive_timeout 1000;
    client_header_timeout 15s;
    client_body_timeout 15s;
    send_timeout 60s;

    # 全局安全配置(作用于所有server块)##########################
    # 1. 协议安全
    # 隐藏Nginx版本号
    server_tokens off;
    # 完全移除Server头
    add_header Server "";

    # 2. 请求限制
    limit_conn_zone $binary_remote_addr zone=global_conn:10m;
    limit_req_zone $binary_remote_addr zone=global_req:10m rate=10r/s;
    limit_conn global_conn 100;

    # 3. 安全头部(会被所有server继承)
	add_header X-Frame-Options "SAMEORIGIN" always;
	add_header X-Content-Type-Options "nosniff" always;
	add_header X-XSS-Protection "1; mode=block" always;
	add_header Referrer-Policy "strict-origin-when-cross-origin" always;
	add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https:; img-src 'self' data: https:; style-src 'self' 'unsafe-inline' https:; font-src 'self' https:;" always;
	add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
	# 防止下载文件直接执行
	add_header X-Download-Options "noopen" always;
	# 禁止跨域策略文件
	add_header X-Permitted-Cross-Domain-Policies "none" always;
    # 6. SSL安全配置(会被所有启用SSL的server继承)
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_stapling on;
    ssl_stapling_verify on;

    # 缓存配置
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=nginx-cache:20m max_size=10g inactive=168h use_temp_path=off;

    # 客户端请求控制
    client_body_buffer_size 512k;
    client_header_buffer_size 4k;
    client_max_body_size 1024M;
    large_client_header_buffers 2 8k;

    # 代理配置
    proxy_connect_timeout 5s;
    proxy_send_timeout 120s;
    proxy_read_timeout 120s;
    proxy_buffer_size 16k;
    proxy_buffers 4 64k;
    proxy_busy_buffers_size 128k;
    proxy_temp_file_write_size 128k;
    proxy_next_upstream http_502 http_504 http_404 error timeout invalid_header;

    # 压缩配置
    gzip on;
    gzip_static on;
    gzip_min_length 1000;
    gzip_buffers 4 16k;
    gzip_comp_level 1;
    gzip_http_version 1.1;
    gzip_vary on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_disable "MSIE [1-6]\.";

    # 文件缓存
    open_file_cache max=655350 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # 包含其他配置(安全配置会自动继承)
    include /etc/nginx/conf.d/*.conf;
}

安全性:隐藏版本、HTTPS 强制、请求限制、安全头部、敏感路径拦截、SSL 强化
性能优化:连接控制、缓存、Gzip、文件缓存、代理优化
日志审计:增强日志记录,便于安全分析
适用于 生产环境,可有效防御常见 Web 攻击(XSS/CSRF/DDoS/目录遍历等)。
所有相关的配置都放在 /etc/nginx/conf.d/*.conf下的。

以下内容需要单独加到单个的 /etc/nginx/conf.d/*.conf中含有server 下的有location方法的案例中

	# 4. 协议强制升级 注意  (这个是80 和443的) 如果带了端口就不要4这个
	# 案例  https://xxxx.com:10014 这种就不要以下4这个方法喔
 	if ($http_x_forwarded_proto != 'https') {
        return 301 https://$host$request_uri;
    }
    # 5. 全局拦截规则(会被所有location继承)拦截敏感文件请求
    location ~* (\.(env|git|svn|htaccess|bak|swp)|config\.|backup/) {
        deny all;
        return 403;
    }
    # 拦截常见攻击路径
    location ~* (wp-admin|admin|console|\.\./) {
        deny all;
        return 403;
    }

如果是WebSocket 单独代理

# WebSocket 代理配置
    location /api/ws {
        proxy_pass http://172.16.17.167:18080;  # 后端 WebSocket 服务地址
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;   # 关键:处理协议升级
        proxy_set_header Connection "upgrade";    # 关键:升级为 WebSocket
        proxy_set_header Host $host;
        # 可选:调优参数
        proxy_read_timeout 86400s;  # 长连接超时时间(根据需求调整)
        proxy_send_timeout 86400s;
   } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

❀͜͡傀儡师

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值