配置Nginx作为静态文件服务器是一个常见且实用的需求。以下是详细的配置步骤和说明:
/etc/nginx/nginx.conf
或/etc/nginx/sites-available/default
)server {
listen 80;
server_name yourdomain.com; # 替换为你的域名或IP
root /path/to/your/files; # 静态文件存放的根目录
index index.html index.htm; # 默认索引文件
location / {
try_files $uri $uri/ =404;
}
}
location / {
autoindex on; # 启用目录列表
autoindex_exact_size off; # 显示文件大小(KB/MB)
autoindex_localtime on; # 使用本地时间
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d; # 缓存30天
add_header Cache-Control "public, no-transform";
}
location ~ /\.ht {
deny all; # 禁止访问.htaccess等隐藏文件
}
location /downloads/ {
limit_rate 200k; # 限制下载速度为200KB/s
}
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;
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;
}
# 限制下载速度
location /large-files/ {
limit_rate 500k;
}
# 启用gzip
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# 错误页面
error_page 404 /404.html;
location = /404.html {
internal;
}
}
sudo nginx -t
sudo systemctl reload nginx
# 或
sudo service nginx reload
location / {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
listen 443 ssl;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location /private/ {
allow 192.168.1.0/24;
deny all;
}
这样你就有了一个功能完善的Nginx静态文件服务器,可以根据实际需求调整配置参数。