插件窝 干货文章 nginx怎么配置静态文件服务器

nginx怎么配置静态文件服务器

Nginx 文件 配置 application 556    来源:    2025-04-22

Nginx 配置静态文件服务器指南

Nginx 是一个高效的 HTTP 服务器,非常适合用作静态文件服务器。以下是配置 Nginx 作为静态文件服务器的详细步骤:

基本配置

  1. 打开 Nginx 配置文件(通常位于 /etc/nginx/nginx.conf/etc/nginx/sites-available/default

  2. 添加或修改 server 块:

server {
    listen 80;
    server_name yourdomain.com;  # 替换为你的域名或IP

    location / {
        root /path/to/your/files;  # 静态文件存放路径
        index index.html index.htm;  # 默认索引文件
        autoindex on;  # 开启目录列表(可选)
    }
}

高级配置选项

1. 启用目录浏览

location / {
    root /path/to/your/files;
    autoindex on;  # 开启目录列表
    autoindex_exact_size off;  # 显示文件大小(KB/MB)
    autoindex_localtime on;  # 使用本地时间
}

2. 设置文件缓存

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    root /path/to/your/files;
    expires 30d;  # 缓存30天
    add_header Cache-Control "public";
}

3. 禁用特定文件访问

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

location ~* \.(log|sql|conf)$ {
    deny all;  # 禁止访问特定扩展名文件
}

4. 启用 gzip 压缩

gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_min_length 1024;
gzip_comp_level 6;

5. 设置字符编码

charset utf-8;

完整示例配置

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

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

    # 启用目录列表
    autoindex on;
    autoindex_exact_size off;
    autoindex_localtime on;

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

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

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

    # 设置字符编码
    charset utf-8;
}

配置完成后

  1. 测试配置是否正确:

    sudo nginx -t
    
  2. 重新加载 Nginx 配置:

    sudo systemctl reload nginx
    # 或者
    sudo service nginx reload
    
  3. 确保目录权限正确:

    sudo chown -R www-data:www-data /path/to/your/files
    sudo chmod -R 755 /path/to/your/files
    

这样你就成功配置了一个基本的静态文件服务器。根据你的具体需求,可以进一步调整上述配置。