如何配置NGINX,使前端可通过URL访问用户上传的头像?
配置NGINX让前端访问上传的头像文件
步骤1:修改NGINX配置文件
在你的server块中新增一个location规则,用来映射头像文件的访问路径。比如用/profile-images作为前端访问的URL前缀,这样前端就能通过这个路径直接访问到后端存储的头像:
server { server_name {my domain name}; # 新增:映射头像文件的访问路径 location /profile-images/ { root /root/backend/MyApp/uploads/; # 开启静态文件缓存,加快访问速度 expires 30d; add_header Cache-Control "public, max-age=2592000"; # 文件不存在时直接返回404,别重定向到前端index.html try_files $uri =404; } location / { root /var/www/app/client; index index.html index.htm; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; try_files $uri $uri/ /index.html; } location /api { proxy_pass http://185.201.8.18:8800; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; # 注意:这里要删掉原有的try_files规则,否则API请求出错会被重定向到前端页面 } }
步骤2:解决权限问题
因为NGINX默认用www-data用户运行,而/root目录的默认权限是700,www-data没权限访问。执行以下命令调整权限:
# 给uploads目录设置可读权限 chmod -R 755 /root/backend/MyApp/uploads/ # 可选:把目录所属组设为www-data,更安全 chown -R root:www-data /root/backend/MyApp/uploads/
访问方式
配置完成并重启NGINX后,前端就能通过类似这样的URL访问头像:https://{你的域名}/profile-images/xxx.jpg
(这里的xxx.jpg是Multer实际存储的文件名,后端返回给前端的地址要对应这个格式)
替代方案(可选)
如果你不想新增NGINX规则,可以把头像目录软链接到前端静态文件目录下:
ln -s /root/backend/MyApp/uploads/profileImages /var/www/app/client/profile-images
这样前端直接通过/profile-images/xxx.jpg就能访问,不需要修改NGINX配置,但同样要确保软链接的权限正确。
内容的提问来源于stack exchange,提问作者Ayushman Verma
相关产品推荐
相关产品推荐

