南安市葬花殡葬网

使用Nginx搭建文件服务器的全过程

2026-03-26 16:41:02 浏览次数:1
详细信息

一、环境准备

1. 安装Nginx(以Ubuntu为例)

# 更新包列表
sudo apt update

# 安装Nginx
sudo apt install nginx -y

# 启动Nginx
sudo systemctl start nginx

# 设置开机自启
sudo systemctl enable nginx

二、基础文件服务器配置

1. 创建文件存储目录

# 创建文件服务器根目录
sudo mkdir -p /var/www/files

# 设置权限
sudo chown -R www-data:www-data /var/www/files
sudo chmod -R 755 /var/www/files

# 创建测试文件
sudo echo "Hello, this is a test file." > /var/www/files/test.txt
sudo touch /var/www/files/example.zip

2. 创建Nginx配置文件

/etc/nginx/sites-available/ 创建配置文件:

sudo nano /etc/nginx/sites-available/fileserver

配置文件内容:

server {
    listen 80;
    server_name files.example.com;  # 改为你的域名或IP

    root /var/www/files;
    index index.html index.htm;

    # 开启自动索引(显示文件列表)
    autoindex on;
    autoindex_exact_size off;  # 显示文件大小(KB/MB)
    autoindex_localtime on;     # 显示本地时间

    # 限制访问(可选)
    location /private/ {
        deny all;
        return 403;
    }

    # 限制文件大小上传(如果需要上传)
    client_max_body_size 100m;

    # 防盗链设置(可选)
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        valid_referers none blocked server_names;
        if ($invalid_referer) {
            return 403;
        }
    }

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

3. 启用配置

# 创建软链接
sudo ln -s /etc/nginx/sites-available/fileserver /etc/nginx/sites-enabled/

# 测试配置
sudo nginx -t

# 重新加载Nginx
sudo systemctl reload nginx

三、高级功能配置

1. 启用SSL/TLS(HTTPS)

# 使用Let's Encrypt获取证书(如有域名)
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d files.example.com

或手动配置SSL:

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

    ssl_certificate /etc/ssl/certs/your_cert.crt;
    ssl_certificate_key /etc/ssl/private/your_key.key;

    # SSL增强设置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    # 其他配置...
}

2. 添加身份验证

# 创建密码文件
sudo apt install apache2-utils
sudo htpasswd -c /etc/nginx/.htpasswd username

在Nginx配置中添加:

location / {
    auth_basic "Restricted Access";
    auth_basic_user_file /etc/nginx/.htpasswd;

    autoindex on;
    # ...其他配置
}

3. 文件上传功能

location /upload {
    # 允许上传
    client_body_temp_path /var/www/temp;
    client_max_body_size 500m;

    # 限制特定文件类型
    if ($request_method = POST) {
        set $deny 0;
        if ($content_type !~ "multipart/form-data") {
            set $deny 1;
        }
    }
}

四、优化配置

1. 缓存设置

location ~* \.(jpg|jpeg|png|gif|ico|css|js|zip|tar|gz|bz2|pdf|txt)$ {
    expires 30d;
    add_header Cache-Control "public, immutable";
}

2. 限速配置

location /downloads/ {
    # 限制下载速度 100KB/s
    limit_rate 100k;

    # 限制并发连接数
    limit_conn addr 5;
}

3. 完整示例配置

# /etc/nginx/sites-available/fileserver

server {
    listen 80;
    listen [::]:80;
    server_name files.yourdomain.com;

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

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name files.yourdomain.com;

    # SSL配置
    ssl_certificate /etc/letsencrypt/live/files.yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/files.yourdomain.com/privkey.pem;

    # 根目录
    root /var/www/files;

    # 基础认证
    auth_basic "File Server";
    auth_basic_user_file /etc/nginx/.htpasswd;

    # 目录列表设置
    autoindex on;
    autoindex_exact_size off;
    autoindex_localtime on;

    # 自定义目录列表样式
    add_before_body /_header.html;
    add_after_body /_footer.html;

    # 文件类型图标(可选)
    location ~* ^.+(\.png|\.jpg|\.jpeg|\.gif)$ {
        autoindex on;
    }

    # 下载文件类型处理
    location ~* \.(zip|rar|tar|gz|bz2|7z)$ {
        add_header Content-Disposition "attachment";
        expires 1h;
    }

    # 图片文件缓存
    location ~* \.(jpg|jpeg|png|gif|ico)$ {
        expires 365d;
        add_header Cache-Control "public, immutable";
    }

    # 视频流媒体支持
    location ~* \.(mp4|webm|avi|mkv)$ {
        mp4;
        mp4_buffer_size 4m;
        mp4_max_buffer_size 10m;
    }

    # 日志
    access_log /var/log/nginx/fileserver-access.log combined;
    error_log /var/log/nginx/fileserver-error.log;

    # 错误页面
    error_page 404 /404.html;
    error_page 403 /403.html;
}

五、网页美化

1. 创建自定义目录列表页面

/var/www/files/ 创建文件:

_header.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>文件服务器</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
        th { background-color: #f2f2f2; }
        .file-icon { width: 20px; margin-right: 10px; }
    </style>
</head>
<body>
    <h1>📁 文件服务器</h1>
    <p>当前目录: <strong>/</strong></p>

_footer.html:

    <hr>
    <p><small>© 2024 文件服务器 | 文件总数: $total_files</small></p>
</body>
</html>

六、管理脚本

创建管理脚本 /usr/local/bin/fileserver-manage.sh:

#!/bin/bash

ACTION=$1
PARAM=$2

case $ACTION in
    "add-user")
        htpasswd /etc/nginx/.htpasswd $PARAM
        ;;
    "remove-user")
        htpasswd -D /etc/nginx/.htpasswd $PARAM
        ;;
    "reload")
        nginx -t && systemctl reload nginx
        ;;
    "add-dir")
        mkdir -p /var/www/files/$PARAM
        chown www-data:www-data /var/www/files/$PARAM
        ;;
    "list-users")
        cat /etc/nginx/.htpasswd | cut -d: -f1
        ;;
    *)
        echo "使用方法:"
        echo "  $0 add-user [用户名]"
        echo "  $0 remove-user [用户名]"
        echo "  $0 reload"
        echo "  $0 add-dir [目录名]"
        echo "  $0 list-users"
        ;;
esac

设置执行权限:

sudo chmod +x /usr/local/bin/fileserver-manage.sh

七、防火墙设置

# 允许HTTP/HTTPS
sudo ufw allow 'Nginx Full'

# 或单独允许端口
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

八、监控和维护

1. 日志轮转

创建 /etc/logrotate.d/nginx-fileserver:

/var/log/nginx/fileserver-*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        systemctl reload nginx
    endscript
}

2. 磁盘空间监控

# 添加到crontab -e
0 * * * * df -h /var/www/files | mail -s "文件服务器磁盘使用情况" admin@example.com

九、故障排查

常见问题检查:

# 检查Nginx配置
sudo nginx -t

# 查看Nginx状态
sudo systemctl status nginx

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

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

# 测试访问
curl -I http://localhost

十、扩展功能

1. WebDAV支持

location /dav/ {
    alias /var/www/files/;
    dav_methods PUT DELETE MKCOL COPY MOVE;
    dav_ext_methods PROPFIND OPTIONS;
    dav_access user:rw group:rw all:r;
    client_max_body_size 100m;
    auth_basic "WebDAV";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

2. 文件搜索功能

需要安装第三方模块或使用外部搜索工具。

这样就完成了一个功能完整的Nginx文件服务器搭建!根据实际需求调整配置参数。

相关推荐