Home > Software design >  Serving images from NGINX
Serving images from NGINX

Time:09-10

I hosted a website on my vps with NGINX where my backend(in Node.js) is in '/root/backend/MyApp' directory. And my frontend(in React.js) is served from '/var/www/app/client' which contains my build files including index.html. I am storing profile image of user via '/api/upload/profileimage' endpoint and the image gets uploaded in '/root/backend/MyApp/uploads/profileImages' directory using 'Multer'. How do configure nginx so that I can serve these uploaded images via a url in frontend? Right now my server configuration looks like:

server {
  server_name {my domain name};

  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 $uri $uri/ /index.html;
  }
}

CodePudding user response:

Try this:

server {
  server_name {my domain name};

  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 $uri $uri/ /index.html;
  }

  location /profileimages/ {
    autoindex on;
    alias /root/backend/MyApp/uploads/profileImages/;
  }
}

You should be able to access the images: yourwebsite.com/profileimages/

  • Related