Nginx常用配置方法

发布时间:2021-06-30 16:45:04 作者:chen
来源:亿速云 阅读:188
# Nginx常用配置方法

## 一、Nginx基础概述

Nginx(发音为"engine x")是一款高性能的HTTP和反向代理服务器,由俄罗斯程序员Igor Sysoev开发。作为轻量级的Web服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,Nginx以高并发、低内存占用著称,全球约32.2%的网站使用Nginx作为Web服务器(数据来源:W3Techs)。

### 核心特性
- 事件驱动架构
- 非阻塞I/O模型
- 热部署能力
- 负载均衡支持
- 高扩展性

## 二、安装与基本命令

### 1. 安装方法(以Ubuntu为例)
```bash
# 添加官方仓库
sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring
curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" | sudo tee /etc/apt/sources.list.d/nginx.list

# 安装Nginx
sudo apt update
sudo apt 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

三、核心配置文件结构

Nginx配置文件通常位于/etc/nginx/nginx.conf,主要包含三个上下文块:

main        # 全局配置(影响所有模块)
events      # 事件处理配置
http        # HTTP服务器配置

典型配置层次:

http {
    server {
        listen 80;
        server_name example.com;
        
        location / {
            root /var/www/html;
            index index.html;
        }
    }
}

四、常用配置场景

1. 静态网站服务

server {
    listen 80;
    server_name example.com;
    
    root /var/www/example;
    index index.html;
    
    location / {
        try_files $uri $uri/ =404;
    }
    
    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
    }
}

2. 反向代理配置

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;
    }
}

3. 负载均衡配置

upstream backend {
    server 192.168.1.100:8000 weight=3;
    server 192.168.1.101:8000;
    server 192.168.1.102:8000 backup;
}

server {
    listen 80;
    server_name app.example.com;
    
    location / {
        proxy_pass http://backend;
    }
}

支持算法: - 轮询(默认) - 加权轮询 - IP哈希 - 最少连接

4. HTTPS配置(Let’s Encrypt)

server {
    listen 443 ssl;
    server_name example.com;
    
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
    ssl_prefer_server_ciphers on;
    
    location / {
        root /var/www/html;
        index index.html;
    }
}

# HTTP强制跳转HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

5. 访问控制

location /admin/ {
    # 基础认证
    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
    
    # IP白名单
    allow 192.168.1.0/24;
    allow 10.0.0.1;
    deny all;
}

生成密码文件:

printf "username:$(openssl passwd -apr1)" > /etc/nginx/.htpasswd

五、性能优化配置

1. 连接优化

events {
    worker_connections 1024;  # 每个worker最大连接数
    multi_accept on;          # 同时接受多个连接
    use epoll;                # Linux高性能事件模型
}

http {
    sendfile on;              # 启用零拷贝传输
    tcp_nopush on;            # 优化数据包发送
    tcp_nodelay on;           # 禁用Nagle算法
    keepalive_timeout 65;     # 保持连接超时
}

2. Gzip压缩

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

3. 缓存配置

# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 30d;
    add_header Cache-Control "public, no-transform";
}

# 代理缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;

server {
    location / {
        proxy_cache my_cache;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
    }
}

六、日志管理

1. 访问日志配置

http {
    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;
    error_log /var/log/nginx/error.log warn;
}

2. 日志分割(通过logrotate)

创建/etc/logrotate.d/nginx

/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

七、安全加固配置

1. 基础安全设置

server {
    # 禁用server tokens
    server_tokens off;
    
    # 防止点击劫持
    add_header X-Frame-Options "SAMEORIGIN";
    
    # XSS防护
    add_header X-XSS-Protection "1; mode=block";
    
    # 内容安全策略
    add_header Content-Security-Policy "default-src 'self'";
}

2. 限制请求方法

location /api/ {
    limit_except GET POST {
        deny all;
    }
}

3. 请求频率限制

limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

location /api/ {
    limit_req zone=api_limit burst=20 nodelay;
}

八、常见问题排查

1. 配置检查命令

# 测试配置语法
sudo nginx -t

# 查看加载的配置文件路径
sudo nginx -T

2. 错误日志位置

3. 性能监控

# 查看活跃连接
netstat -anp | grep nginx

# 查看进程状态
top -p $(pgrep nginx | tr '\n' ',' | sed 's/,$//')

九、进阶配置示例

1. WebSocket代理

location /ws/ {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

2. 多域名配置

server {
    listen 80;
    server_name example.com www.example.com;
    
    location / {
        root /var/www/example;
    }
}

server {
    listen 80;
    server_name blog.example.com;
    
    location / {
        proxy_pass http://localhost:2368;
    }
}

3. 自定义错误页面

error_page 404 /404.html;
location = /404.html {
    root /usr/share/nginx/html;
    internal;
}

十、总结

本文涵盖了Nginx从基础安装到高级配置的多个方面,包括: 1. 静态资源服务配置 2. 反向代理与负载均衡 3. HTTPS安全配置 4. 性能优化技巧 5. 安全加固方案 6. 常见问题排查方法

实际生产环境中,建议: - 使用nginx -t测试所有配置变更 - 通过灰度发布逐步应用重大修改 - 定期检查错误日志和访问日志 - 保持Nginx版本更新以获得安全补丁

通过合理配置,Nginx可以轻松应对高并发场景,成为现代Web架构中不可或缺的组件。 “`

推荐阅读:
  1. MongoDB常用配置及维护方法
  2. Nginx常用配置详解(三)——http协议模块配置

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

nginx

上一篇:php中rpc框架的作用是什么

下一篇:php中require_once如何使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》