Nginx是一个高性能的HTTP和反向代理服务器,非常适合用来搭建图片服务器。以下是详细的搭建步骤:
# Ubuntu/Debian
sudo apt update
sudo apt install nginx
# CentOS/RHEL
sudo yum install epel-release
sudo yum install nginx
从官网下载Windows版Nginx并解压:http://nginx.org/en/download.html
编辑Nginx配置文件(通常在/etc/nginx/nginx.conf
或/etc/nginx/conf.d/default.conf
):
server {
listen 80;
server_name your-domain.com; # 替换为你的域名或IP
# 图片存储目录
location /images/ {
alias /path/to/your/images/; # 替换为实际的图片存储路径
autoindex on; # 开启目录浏览(可选)
# 设置缓存
expires 30d;
add_header Cache-Control "public";
# 允许跨域访问(可选)
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
}
# 图片防盗链配置(可选)
location ~* \.(jpg|jpeg|png|gif|webp)$ {
valid_referers none blocked your-domain.com *.your-domain.com;
if ($invalid_referer) {
return 403;
}
}
}
sudo mkdir -p /path/to/your/images
sudo chown -R www-data:www-data /path/to/your/images # Ubuntu
# 或
sudo chown -R nginx:nginx /path/to/your/images # CentOS
sudo nginx -t # 测试配置是否正确
sudo systemctl restart nginx # Ubuntu/CentOS 7+
# 或
sudo service nginx restart # 旧版本
gzip on;
gzip_types image/svg+xml image/x-icon image/jpeg image/png image/gif;
location ~* /images/(.+)\.(jpg|jpeg|png|gif)$ {
image_filter resize 800 600;
image_filter_buffer 10M;
}
location ~* /images/(.+)\.(jpg|jpeg|png)$ {
webp on;
webp_quality 85;
}
limit_except GET {
deny all;
}
limit_req_zone $binary_remote_addr zone=img:10m rate=10r/s;
location /images/ {
limit_req zone=img burst=20;
}
server_tokens off;
上传一张图片到你的图片目录,然后通过浏览器访问:
http://your-domain.com/images/your-image.jpg
403 Forbidden错误:
chmod -R 755 /path/to/your/images
chown -R nginx:nginx /path/to/your/images
404 Not Found错误:
性能优化:
sendfile on;
tcp_nopush on;
通过以上步骤,你就可以成功搭建一个高性能的Nginx图片服务器了。