编辑conf/nginx.conf
文件,在http块内添加或修改server配置:
server {
listen 80;
server_name localhost; # 可改为你的域名或IP
# 图片服务配置
location /images/ {
alias D:/images/; # 图片存放的实际路径
autoindex on; # 开启目录浏览(可选)
# 设置缓存和过期时间
expires 30d;
add_header Cache-Control "public";
# 允许跨域访问(可选)
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET';
}
# 其他配置...
}
start nginx
tasklist /fi "imagename eq nginx.exe"
http://localhost/images/test.jpg
http://localhost/images/
可查看目录列表gzip on;
gzip_types image/jpeg image/png image/gif;
location /images/ {
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
return 403;
# 或返回一张默认图片: rewrite ^ /images/default.jpg;
}
}
location ~* \.(jpg|jpeg|png|gif|ico)$ {
expires 365d;
add_header Cache-Control "public, no-transform";
}
403 Forbidden错误
autoindex on;
图片无法显示
性能优化
sendfile on;
worker_processes 4;
(根据CPU核心数调整)nginx -s reload
nginx -s stop
nginx -s quit
通过以上步骤,你就可以在Windows系统上成功搭建一个Nginx图片服务器了。