儋州市本地信息网

Nginx服务部署与配置全过程

2026-03-26 22:42:02 浏览次数:1
详细信息

一、环境准备与安装

1. 系统要求

2. 安装Nginx

Ubuntu/Debian:

sudo apt update
sudo apt install nginx

CentOS/RHEL:

sudo yum install epel-release
sudo yum install nginx

源码编译安装(最新版本):

wget http://nginx.org/download/nginx-1.24.0.tar.gz
tar -zxvf nginx-1.24.0.tar.gz
cd nginx-1.24.0
./configure --prefix=/usr/local/nginx
make
sudo make install

二、Nginx目录结构

/etc/nginx/                    # 主配置目录
├── nginx.conf                 # 主配置文件
├── conf.d/                    # 额外配置文件目录
├── sites-available/           # 可用站点配置
├── sites-enabled/             # 启用的站点配置(符号链接)
├── modules-available/         # 可用模块
└── modules-enabled/           # 启用模块
/var/log/nginx/                # 日志目录
├── access.log                 # 访问日志
└── error.log                  # 错误日志
/usr/share/nginx/html/         # 默认网站根目录

三、配置文件详解

1. 主配置文件结构 (nginx.conf)

# 全局块
user nginx;                    # 运行用户
worker_processes auto;         # 工作进程数(建议设为CPU核心数)
error_log /var/log/nginx/error.log warn;  # 错误日志
pid /var/run/nginx.pid;        # PID文件位置

# Events块
events {
    worker_connections 1024;   # 每个worker最大连接数
    use epoll;                 # 事件驱动模型(Linux)
    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;
    client_max_body_size 20m;  # 上传文件大小限制

    # Gzip压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml;

    # 包含其他配置
    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/html;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

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

    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
    }
}

2. 反向代理配置(Node.js/Python应用)

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 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}

3. PHP-FPM配置(PHP应用)

server {
    listen 80;
    server_name php.example.com;
    root /var/www/phpapp/public;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;

        # 安全设置
        fastcgi_param PHP_VALUE "upload_max_filesize=20M \n post_max_size=20M";
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
    }
}

五、SSL/TLS配置(HTTPS)

1. 使用Let's Encrypt免费证书

# 安装certbot
sudo apt install certbot python3-certbot-nginx

# 获取证书
sudo certbot --nginx -d example.com -d www.example.com

2. 手动配置SSL

server {
    listen 443 ssl http2;
    server_name example.com;

    # SSL证书
    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    # SSL优化
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
    ssl_prefer_server_ciphers off;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_stapling on;
    ssl_stapling_verify on;

    # HSTS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # 网站内容配置
    root /var/www/html;
    index index.html;
}

3. HTTP重定向到HTTPS

server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

六、安全配置

1. 基本安全设置

# 隐藏Nginx版本号
server_tokens off;

# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;

# CSP策略(示例)
add_header Content-Security-Policy "default-src 'self';" always;

2. 限制访问

# 限制特定IP访问管理后台
location /admin/ {
    allow 192.168.1.0/24;
    allow 10.0.0.1;
    deny all;

    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

# 限制请求方法
if ($request_method !~ ^(GET|POST|HEAD)$) {
    return 405;
}

# 限制机器人访问
location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
}

七、性能优化配置

1. 连接优化

# 在events块中
events {
    worker_connections 4096;
    use epoll;
    multi_accept on;
}

# 在http块中
http {
    # TCP优化
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    # 连接超时
    keepalive_timeout 30;
    keepalive_requests 100;

    # 客户端超时
    client_body_timeout 12;
    client_header_timeout 12;
    send_timeout 10;

    # 缓冲区优化
    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    client_max_body_size 8m;
    large_client_header_buffers 4 4k;
}

2. 缓存配置

# 代理缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
proxy_cache_key "$scheme$request_method$host$request_uri";

server {
    location / {
        proxy_cache my_cache;
        proxy_cache_valid 200 302 60m;
        proxy_cache_valid 404 1m;
        add_header X-Cache-Status $upstream_cache_status;
    }
}

八、常用命令与管理

1. 服务管理命令

# 启动Nginx
sudo systemctl start nginx

# 停止Nginx
sudo systemctl stop nginx

# 重启Nginx
sudo systemctl restart nginx

# 重新加载配置(不中断服务)
sudo systemctl reload nginx

# 查看状态
sudo systemctl status nginx

# 开机自启
sudo systemctl enable nginx

2. 配置文件操作

# 测试配置语法
sudo nginx -t

# 显示编译配置
nginx -V

# 创建站点配置符号链接
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

# 查看日志
sudo tail -f /var/log/nginx/access.log
sudo tail -f /var/log/nginx/error.log

九、故障排查

常见问题与解决:

端口占用检查

sudo netstat -tlnp | grep :80
sudo lsof -i :80

权限问题

# 确保nginx用户有目录访问权限
sudo chown -R nginx:nginx /var/www/
sudo chmod -R 755 /var/www/

配置检查


# 详细错误信息
sudo nginx -t -c /etc/nginx/nginx.conf
查看运行配置

ps aux | grep nginx


4. **性能监控**
```bash
# 查看连接状态
ss -tan | grep :80 | wc -l

# Nginx状态模块(需要配置)
location /nginx_status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
}

十、高级配置示例

负载均衡配置

upstream backend {
    least_conn;  # 最少连接算法
    # ip_hash;   # IP哈希算法
    # fair;      # 响应时间算法

    server backend1.example.com:8080 weight=3;
    server backend2.example.com:8080;
    server backend3.example.com:8080 backup;

    keepalive 32;  # 长连接池
}

server {
    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

WebSocket支持

location /ws/ {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_read_timeout 86400s;
    proxy_send_timeout 86400s;
}

部署检查清单

[ ] 防火墙开放80/443端口 [ ] SELinux/AppArmor配置 [ ] 日志轮转配置 [ ] 备份配置文件 [ ] 监控设置(如fail2ban) [ ] 定期更新SSL证书 [ ] 启用访问日志分析

这个完整的配置指南应该能满足大多数Nginx部署需求。根据具体应用场景调整相应配置即可。

相关推荐