泰安市中国丧葬服务网

Nginx服务器部署详细代码实例

2026-03-26 10:38:01 浏览次数:0
详细信息

一、Nginx安装(Ubuntu/Debian)

# 更新系统包
sudo apt update
sudo apt upgrade -y

# 安装Nginx
sudo apt install nginx -y

# 启动Nginx
sudo systemctl start nginx
sudo systemctl enable nginx

# 检查状态
sudo systemctl status nginx

二、基础配置文件结构

/etc/nginx/
├── nginx.conf          # 主配置文件
├── sites-available/    # 可用站点配置
├── sites-enabled/      # 已启用站点(符号链接)
├── conf.d/            # 额外配置
└── ssl/               # SSL证书目录(需手动创建)

三、主配置文件示例(nginx.conf)

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {
    # 基础设置
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    server_tokens off;

    # MIME类型
    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;
    error_log /var/log/nginx/error.log warn;

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

    # 虚拟主机配置
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

四、静态网站配置示例

创建 /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;

    # 访问日志
    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 ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

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

启用站点:

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t  # 测试配置
sudo systemctl reload nginx

五、PHP应用配置(如WordPress)

server {
    listen 80;
    server_name blog.example.com;
    root /var/www/wordpress;
    index index.php index.html index.htm;

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

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    # WordPress固定链接重写
    location ~ /wp-admin/ {
        rewrite ^/wp-admin/(.*)$ /wp-admin/$1 break;
    }

    # 静态文件缓存
    location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ {
        expires max;
        log_not_found off;
    }
}

六、SSL证书配置(Let's Encrypt)

server {
    listen 80;
    server_name example.com www.example.com;
    # 重定向到HTTPS
    return 301 https://$server_name$request_uri;
}

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

    # SSL证书路径(Certbot自动生成)
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # 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_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # HSTS头(谨慎使用)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    root /var/www/example.com/html;
    index index.html;

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

使用Certbot自动获取证书:

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com

七、反向代理配置

server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://localhost:3000;  # 代理到本地Node.js应用

        # 代理头设置
        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;

        # WebSocket支持
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    # API限流
    location /api/ {
        limit_req zone=api burst=10 nodelay;
        proxy_pass http://localhost:3000;
    }
}

# 限流区域定义(放在http块中)
limit_req_zone $binary_remote_addr zone=api:10m rate=1r/s;

八、负载均衡配置

upstream backend_servers {
    # 负载均衡算法:least_conn(最少连接)
    least_conn;

    # 后端服务器列表
    server 192.168.1.101:8080 weight=3 max_fails=3 fail_timeout=30s;
    server 192.168.1.102:8080 weight=2;
    server 192.168.1.103:8080 weight=1 backup;  # 备份服务器

    # 会话保持(可选)
    ip_hash;
}

server {
    listen 80;
    server_name app.example.com;

    location / {
        proxy_pass http://backend_servers;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;

        # 健康检查
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
    }
}

九、常用Nginx命令

# 测试配置文件
sudo nginx -t

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

# 停止服务
sudo systemctl stop nginx

# 重启服务
sudo systemctl restart nginx

# 查看运行状态
sudo systemctl status nginx

# 查看版本
nginx -v

# 查看编译参数
nginx -V

十、Docker部署示例

docker-compose.yml

version: '3.8'
services:
  nginx:
    image: nginx:latest
    container_name: nginx-web
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./sites:/etc/nginx/sites-enabled
      - ./html:/usr/share/nginx/html
      - ./ssl:/etc/nginx/ssl
      - ./logs:/var/log/nginx
    networks:
      - web-network
    restart: unless-stopped

networks:
  web-network:
    driver: bridge

十一、安全加固建议

隐藏Nginx版本信息

server_tokens off;

限制请求方法

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

防止点击劫持

add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;

限制客户端body大小

client_max_body_size 10m;

十二、性能优化建议

# 调整工作进程
worker_processes auto;

# 每个工作进程连接数
events {
    worker_connections 10240;
    use epoll;
    multi_accept on;
}

# 缓冲区优化
client_body_buffer_size 128k;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;

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

故障排查命令

# 查看错误日志
tail -f /var/log/nginx/error.log

# 查看访问日志
tail -f /var/log/nginx/access.log

# 检查端口监听
sudo netstat -tlnp | grep nginx

# 检查进程
ps aux | grep nginx

# 测试配置
sudo nginx -t -c /etc/nginx/nginx.conf

这个配置实例涵盖了Nginx部署的主要场景,您可以根据实际需求进行调整。记得在修改配置后使用 nginx -t 测试语法,然后重新加载配置。

相关推荐