IWA
2025-08-27
点 赞
0
热 度
6
评 论
0

Nginx 部署及使用基础教程

什么是 Nginx?

Nginx 是一款高性能的开源 Web 服务器软件,由 Igor Sysoev 于 2004 年首次发布。它不仅可以用作 HTTP 服务器,还可以作为反向代理服务器、邮件代理服务器和通用的 TCP/UDP 代理服务器。Nginx 采用事件驱动的异步架构,能够高效处理大量并发连接,同时保持较低的内存占用。

Nginx 的主要特性

  • 高性能:采用事件驱动架构,能够处理数万个并发连接

  • 低内存消耗:相比传统服务器,在相同负载下内存使用更少

  • 高可靠性:稳定的运行表现和优秀的错误处理机制

  • 模块化设计:通过模块扩展功能,保持核心精简

  • 热部署:支持在不停止服务的情况下更新配置和二进制文件

安装 Nginx

Ubuntu/Debian 系统安装

更新软件包列表并安装 Nginx:

sudo apt update
sudo apt install nginx

安装完成后验证版本:

nginx -v

CentOS/RHEL 系统安装

首先添加 EPEL 仓库,然后安装 Nginx:

sudo yum install epel-release
sudo yum install nginx

从源码编译安装

下载最新源码包:

wget http://nginx.org/download/nginx-1.18.0.tar.gz
tar -zxvf nginx-1.18.0.tar.gz
cd nginx-1.18.0

配置编译选项:

./configure --prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-http_gzip_static_module

编译并安装:

make
sudo make install

Nginx 服务管理

系统服务管理

启动 Nginx 服务:

sudo systemctl start nginx

设置开机自启:

sudo systemctl enable nginx

停止服务:

sudo systemctl stop nginx

重启服务:

sudo systemctl restart nginx

重新加载配置(不中断服务):

sudo systemctl reload nginx

查看服务状态:

sudo systemctl status nginx

进程管理

查看 Nginx 进程:

ps aux | grep nginx

优雅停止(处理完当前请求后停止):

sudo nginx -s quit

立即停止:

sudo nginx -s stop

Nginx 配置文件结构

主配置文件

主配置文件通常位于 /etc/nginx/nginx.conf,包含以下主要部分:

# 全局配置块
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Events 配置块
events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

# HTTP 配置块
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/*;
}

虚拟主机配置

创建新的站点配置文件:

sudo nano /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 index.php;
    
    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;
    
    location / {
        try_files $uri $uri/ =404;
    }
    
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }
    
    location ~ /\.ht {
        deny all;
    }
}

启用站点配置:

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

常用配置详解

静态文件服务配置

server {
    listen 80;
    server_name static.example.com;
    
    root /var/www/static;
    
    location / {
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
    }
    
    # 静态文件缓存配置
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}

反向代理配置

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;
    }
    
    # 负载均衡配置
    upstream backend {
        server 192.168.1.10:8080 weight=3;
        server 192.168.1.11:8080 weight=2;
        server 192.168.1.12:8080 weight=1;
    }
}

SSL/TLS 配置

server {
    listen 443 ssl http2;
    server_name secure.example.com;
    
    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # HSTS 头
    add_header Strict-Transport-Security "max-age=31536000" always;
}

性能优化配置

工作进程优化

worker_processes auto;  # 自动根据 CPU 核心数设置
worker_rlimit_nofile 100000;  # 每个 worker 进程能打开的文件描述符数量

events {
    worker_connections 4096;  # 每个 worker 进程的最大连接数
    use epoll;  # 使用 epoll 事件模型
    multi_accept on;  # 一次接受所有新连接
}

HTTP 性能优化

http {
    # 缓冲区和超时设置
    client_body_buffer_size 128k;
    client_max_body_size 10m;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 4k;
    
    # 超时设置
    client_body_timeout 12;
    client_header_timeout 12;
    keepalive_timeout 15;
    send_timeout 10;
    
    # Gzip 压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml;
}

日志管理

访问日志配置

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
               '$status $body_bytes_sent "$http_referer" '
               '"$http_user_agent" "$http_x_forwarded_for"';
               
log_format compression '$remote_addr - $remote_user [$time_local] '
                      '"$request" $status $body_bytes_sent '
                      '"$http_referer" "$http_user_agent" "$gzip_ratio"';

access_log /var/log/nginx/access.log main buffer=32k flush=5m;

错误日志配置

error_log /var/log/nginx/error.log warn;

安全配置

基本安全设置

server {
    # 隐藏 Nginx 版本信息
    server_tokens off;
    
    # 防止点击劫持
    add_header X-Frame-Options SAMEORIGIN;
    
    # XSS 保护
    add_header X-XSS-Protection "1; mode=block";
    
    # 禁止不需要的 HTTP 方法
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }
}

限制访问

# 限制连接频率
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

# 限制并发连接数
limit_conn_zone $binary_remote_addr zone=addr:10m;

location /api/ {
    limit_req zone=one burst=5;
    limit_conn addr 10;
}

监控和调试

状态监控

启用状态模块:

location /nginx_status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
}

调试技巧

检查配置语法:

sudo nginx -t

查看编译参数:

nginx -V

实时查看访问日志:

tail -f /var/log/nginx/access.log

实时查看错误日志:

tail -f /var/log/nginx/error.log

常见问题排查

权限问题

确保 Nginx 用户有访问网站文件的权限:

sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html

端口冲突

检查端口占用情况:

sudo netstat -tulpn | grep :80

配置错误

详细错误信息查看:

sudo nginx -t
sudo tail -f /var/log/nginx/error.log

最佳实践建议

  1. 保持更新:定期更新 Nginx 到最新稳定版本

  2. 最小权限原则:使用非 root 用户运行 Nginx

  3. 配置文件管理:使用 include 指令组织配置文件

  4. 日志轮转:配置 logrotate 管理日志文件

  5. 监控告警:设置监控系统关注 Nginx 状态

  6. 备份配置:定期备份重要的配置文件

  7. 测试环境:在生产环境部署前充分测试配置


用键盘敲击出的不只是字符,更是一段段生活的剪影、一个个心底的梦想。希望我的文字能像一束光,在您阅读的瞬间,照亮某个角落,带来一丝温暖与共鸣。

IWA

estp 企业家

具有版权性

请您在转载、复制时注明本文 作者、链接及内容来源信息。 若涉及转载第三方内容,还需一同注明。

具有时效性

文章目录

IWA的艺术编程,为您导航全站动态

19 文章数
9 分类数
9 评论数
23标签数
最近评论
M丶Rock

M丶Rock


😂

M丶Rock

M丶Rock


感慨了

M丶Rock

M丶Rock


厉害了

M丶Rock

M丶Rock


6666666666666666666

M丶Rock

M丶Rock


6666666666666666666

访问统计