插件窝 干货文章 nginx服务器搭建和配置的方法

nginx服务器搭建和配置的方法

Nginx 配置 example server 489    来源:    2025-04-21

Nginx服务器搭建与配置指南

一、Nginx简介

Nginx是一款高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP代理服务器。它以高并发、低内存占用和模块化架构著称。

二、安装Nginx

Linux系统安装

Ubuntu/Debian

sudo apt update
sudo apt install nginx
sudo systemctl start nginx
sudo systemctl enable nginx

CentOS/RHEL

sudo yum install epel-release
sudo yum install nginx
sudo systemctl start nginx
sudo systemctl enable nginx

Windows系统安装

  1. 从官网下载Windows版本Nginx
  2. 解压到指定目录
  3. 运行nginx.exe

macOS安装

brew install nginx
brew services start nginx

三、基本配置

配置文件结构

  • 主配置文件:/etc/nginx/nginx.conf
  • 站点配置文件:/etc/nginx/conf.d//etc/nginx/sites-available/
  • 日志文件:/var/log/nginx/

常用配置指令

# 用户和工作进程配置
user www-data;
worker_processes auto;

# 事件模块配置
events {
    worker_connections 1024;
    multi_accept on;
}

# HTTP模块配置
http {
    include 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;

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

四、虚拟主机配置

基本虚拟主机配置

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

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

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

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;

    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

HTTPS配置(使用Let's Encrypt)

  1. 安装Certbot
sudo apt install certbot python3-certbot-nginx
  1. 获取证书
sudo certbot --nginx -d example.com -d www.example.com
  1. 自动生成的HTTPS配置示例
server {
    listen 443 ssl;
    server_name example.com www.example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

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

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

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

五、高级配置

负载均衡

upstream backend {
    server backend1.example.com weight=5;
    server backend2.example.com;
    server backend3.example.com;
    server backup.example.com backup;
}

server {
    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

反向代理

server {
    listen 80;
    server_name proxy.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;
    }
}

静态文件缓存

server {
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;
        add_header Cache-Control "public, no-transform";
    }
}

六、安全配置

基本安全设置

server {
    # 禁用不必要的HTTP方法
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }

    # 隐藏Nginx版本信息
    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';";

    # 防止MIME类型嗅探
    add_header X-Content-Type-Options "nosniff";
}

限制访问

# 限制IP访问
location /admin {
    allow 192.168.1.0/24;
    deny all;
}

# 限制请求速率
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

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

七、性能优化

Gzip压缩

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

连接优化

# 调整缓冲区大小
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 2 1k;

# 超时设置
client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;

八、常用命令

# 启动Nginx
sudo systemctl start nginx

# 停止Nginx
sudo systemctl stop nginx

# 重启Nginx
sudo systemctl restart nginx

# 重新加载配置
sudo systemctl reload nginx

# 检查配置语法
sudo nginx -t

# 查看Nginx状态
sudo systemctl status nginx

九、日志分析

查看访问日志

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

使用GoAccess进行实时分析

goaccess /var/log/nginx/access.log --log-format=COMBINED

十、常见问题排查

  1. 端口冲突:检查是否有其他服务占用了80或443端口

    sudo netstat -tulnp | grep ':80\|:443'
    
  2. 权限问题:确保Nginx用户有访问网站目录的权限

    sudo chown -R www-data:www-data /var/www/example.com
    
  3. 配置错误:使用nginx -t测试配置

  4. 502 Bad Gateway:通常是后端服务未运行或代理配置错误

  5. 403 Forbidden:检查目录权限和index文件是否存在

通过以上步骤和配置,您可以搭建和配置一个高性能、安全的Nginx服务器。根据实际需求调整配置参数以获得最佳性能。