Nginx 搭建文件服务器

使用 Nginx 搭建文件服务器

为什么选择 Nginx 作为文件服务器

1. 性能优势

  • 高并发处理 - 轻量级,支持大量并发连接
  • 低资源消耗 - 内存占用少,CPU使用率低
  • 静态文件服务 - 专门优化过的静态文件传输
  • 高稳定性 - 长期运行稳定可靠

2. 功能特性

  • 简单的配置 - 配置文件简洁明了
  • HTTP基本认证 - 内置访问控制
  • 目录浏览 - 自动显示目录内容
  • 防盗链 - 防止他人盗用资源

基础配置

1. 安装 Nginx

bash 复制代码
# Ubuntu/Debian
sudo apt update
sudo apt install nginx

# CentOS/RHEL
sudo yum install nginx
# 或者使用 dnf (较新版本)
sudo dnf install nginx

# Windows
# 下载安装包并运行

2. 基本文件服务器配置

nginx 复制代码
# /etc/nginx/sites-available/fileserver
server {
    listen 80;
    server_name your-domain.com;  # 或者使用IP地址

    # 文件服务器根目录
    location / {
        root /var/www/files;  # 指定文件存储目录
        autoindex on;         # 启用目录浏览
        autoindex_exact_size off;  # 文件大小显示为人类可读格式
        autoindex_localtime on;    # 显示本地时间而非GMT时间
        
        # 设置基本认证(可选)
        auth_basic "Restricted Access";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
    
    # 限制访问日志(可选)
    access_log /var/log/nginx/fileserver_access.log;
    error_log /var/log/nginx/fileserver_error.log;
}

3. 创建认证文件

bash 复制代码
# 安装htpasswd工具
sudo apt install apache2-utils  # Ubuntu/Debian
# 或
sudo yum install httpd-tools    # CentOS/RHEL

# 创建用户和密码文件
sudo htpasswd -c /etc/nginx/.htpasswd username
# 系统会提示输入密码

高级配置

1. HTTPS 配置

nginx 复制代码
server {
    listen 443 ssl http2;
    server_name your-domain.com;

    ssl_certificate /path/to/your/certificate.crt;
    ssl_certificate_key /path/to/your/private.key;
    
    # SSL 安全配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    location / {
        root /var/www/files;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
        
        # 限制文件上传大小
        client_max_body_size 100M;
    }
}

# HTTP 重定向到 HTTPS
server {
    listen 80;
    server_name your-domain.com;
    return 301 https://$server_name$request_uri;
}

2. 防盗链配置

nginx 复制代码
server {
    listen 80;
    server_name your-domain.com;

    location /files/ {
        root /var/www;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
        
        # 防盗链配置
        valid_referers none blocked server_names *.your-domain.com;
        if ($invalid_referer) {
            return 403;
        }
    }
}

3. 压缩传输

nginx 复制代码
server {
    listen 80;
    server_name your-domain.com;

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

    location / {
        root /var/www/files;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
    }
}

4. 自定义文件类型处理

nginx 复制代码
server {
    listen 80;
    server_name your-domain.com;

    # 自定义MIME类型
    location ~* \.pdf$ {
        root /var/www/files;
        add_header Content-Type application/pdf;
        add_header Content-Disposition attachment;
    }
    
    location ~* \.(jpg|jpeg|png|gif)$ {
        root /var/www/files;
        expires 30d;  # 缓存30天
        add_header Cache-Control "public, immutable";
    }
    
    location ~* \.txt$ {
        root /var/www/files;
        add_header Content-Type text/plain;
    }
}

完整的生产环境配置

nginx 复制代码
# /etc/nginx/sites-available/fileserver.conf
upstream fileserver_backend {
    server 127.0.0.1:8080;  # 如果需要反向代理到应用服务器
}

server {
    listen 80;
    listen [::]:80;
    server_name your-domain.com;

    # 重定向到HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name your-domain.com;

    # SSL证书配置
    ssl_certificate /path/to/certificate.crt;
    ssl_certificate_key /path/to/private.key;
    ssl_trusted_certificate /path/to/ca.crt;

    # SSL安全配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    # 安全头
    add_header X-Frame-Options DENY always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Strict-Transport-Security "max-age=63072000" always;

    # 文件上传限制
    client_max_body_size 100M;

    # 静态文件服务
    location / {
        root /var/www/files;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
        
        # 缓存静态文件
        expires 1d;
        add_header Cache-Control "public, immutable";
        
        # 防盗链
        valid_referers none blocked server_names *.your-domain.com;
        if ($invalid_referer) {
            return 403;
        }
    }

    # 特定目录配置
    location ^~ /private/ {
        root /var/www;
        auth_basic "Private Area - Authorization Required";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }

    # 日志配置
    access_log /var/log/nginx/fileserver_access.log;
    error_log /var/log/nginx/fileserver_error.log;
}

# 服务状态监控(可选)
server {
    listen 127.0.0.1:8080;  # 仅本地访问
    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }
}

启用配置

1. 启用站点

bash 复制代码
# 创建软链接(Ubuntu/Debian)
sudo ln -s /etc/nginx/sites-available/fileserver.conf /etc/nginx/sites-enabled/

# 或者直接复制配置文件
sudo cp /etc/nginx/sites-available/fileserver.conf /etc/nginx/conf.d/fileserver.conf

# 测试配置
sudo nginx -t

# 重新加载配置
sudo systemctl reload nginx
# 或
sudo nginx -s reload

2. 创建文件目录

bash 复制代码
# 创建文件存储目录
sudo mkdir -p /var/www/files
sudo chown www-data:www-data /var/www/files
sudo chmod 755 /var/www/files

# 或者使用自定义目录
mkdir -p ~/shared-files
# 在配置中使用绝对路径

文件上传功能(配合后端)

1. Nginx 配置(配合后端处理上传)

nginx 复制代码
server {
    listen 80;
    server_name your-domain.com;

    # 文件上传处理(需要后端应用)
    location /upload {
        proxy_pass http://127.0.0.1:3000;  # 后端应用地址
        client_max_body_size 100M;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    # 文件访问
    location /files/ {
        root /var/www;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
    }
}

2. 简单的上传页面

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
    <h2>文件上传</h2>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" required>
        <button type="submit">上传</button>
    </form>
</body>
</html>

安全配置

1. 访问控制

nginx 复制代码
# IP白名单
location / {
    root /var/www/files;
    allow 192.168.1.0/24;  # 允许特定IP段
    allow 127.0.0.1;
    deny all;              # 拒绝其他所有IP
    autoindex on;
}

# 基本认证
location /protected/ {
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

2. 防止恶意文件上传

nginx 复制代码
# 禁止执行脚本文件
location ~* \.(php|pl|py|jsp|asp|sh|cgi)$ {
    deny all;
    return 404;
}

# 限制上传文件类型
location /uploads {
    location ~* \.(jpg|jpeg|png|gif|pdf|doc|docx|txt|zip|rar)$ {
        # 允许的文件类型
    }
    
    location ~* \.(php|html|htm|js|css)$ {
        deny all;
        return 404;
    }
}

性能优化

1. 缓存配置

nginx 复制代码
# 启用文件缓存
location / {
    root /var/www/files;
    autoindex on;
    autoindex_exact_size off;
    autoindex_localtime on;
    
    # 设置缓存
    expires 1y;
    add_header Cache-Control "public, immutable";
    
    # 启用sendfile
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
}

2. Gzip压缩

nginx 复制代码
# 全局启用Gzip
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied expired no-cache no-store private must-revalidate auth;
gzip_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/javascript
    application/xml+rss
    application/json;

管理和监控

1. 常用命令

bash 复制代码
# 启动Nginx
sudo systemctl start nginx

# 停止Nginx
sudo systemctl stop nginx

# 重启Nginx
sudo systemctl restart nginx

# 重载配置
sudo systemctl reload nginx

# 检查配置
sudo nginx -t

# 查看状态
sudo systemctl status nginx

2. 日志查看

bash 复制代码
# 查看访问日志
sudo tail -f /var/log/nginx/access.log

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

# 统计访问量
sudo awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr

总结

使用 Nginx 作为文件服务器的优势:

  • 高性能 - 静态文件服务效率极高
  • 配置简单 - 配置文件直观易懂
  • 功能丰富 - 支持认证、防盗链、缓存等
  • 安全可靠 - 企业级稳定性
  • 资源占用少 - 轻量级,适合各种规模部署

Nginx 是搭建文件服务器的理想选择,特别适合用于静态文件分发、内网文件共享、CDN节点等场景。

相关推荐
郝学胜-神的一滴5 分钟前
深入理解Linux中的Try锁机制
linux·服务器·开发语言·c++·程序人生
Anakki6 分钟前
企业级 Elastic Stack 集成架构:Spring Boot 3.x 与 Elasticsearch 8.x 深度实践指南
运维·jenkins·springboot·elastic search
Java后端的Ai之路6 分钟前
【AutoDL算力平台】-MobaXterm 连接 AutoDL 并上传文件资源(图文 + 实操)
服务器·网络·mobaxterm·autodl算力平台
阿巴~阿巴~9 分钟前
NAT技术:互联网连接的隐形桥梁
服务器·网络·网络协议·架构·智能路由器·nat·正反向代理
DevOps-IT11 分钟前
HTTP状态码(常见 HTTP Status Code 查询)
运维·服务器·网络·网络协议·http
YJlio13 分钟前
Registry Usage (RU) 学习笔记(15.5):注册表内存占用体检与 Hive 体量分析
服务器·windows·笔记·python·学习·tcp/ip·django
释怀不想释怀17 分钟前
Docker(安装软件)
运维·docker·容器
阿巴~阿巴~19 分钟前
打通局域网“最后一公里”:ARP协议原理、流程与安全解析
服务器·网络·网络协议·tcp/ip·tcp·ipv4·arp
网硕互联的小客服20 分钟前
服务器 CPU 温度过高需要进行的物理处理和软件处理有哪些?
运维·服务器
北辰当尹31 分钟前
【实习之旅】Kali虚拟机桥接模式ping通百度
java·服务器·桥接模式