Search code examples
configurationnginxconfiguration-files

How to serve images with nginx


I am completely new to nginx and I am asked to find a way to serve Map Tiles that are separated according to the zoom levels. The image file structure is like ~/data/images/7/65/70.png where 7 is the zoom level, 65 and 70 are the lon-lat values. The folder 65 contains many files such as 71.png, 72.png and etc.

I have installed Nginx properly and I can get Welcome to nginx message. I have followed the instructions in http://nginx.org/en/docs/beginners_guide.html and created the /data/www and /data/images directories. I have placed index.html file under /data/www and tile images under /data/images. Then I modified the configuration file by adding following lines in http tags:

server {
    location / {
        root /data/www;
    }

    location /images/ {
        root /data;
    }
}

After reloading the config file and entering localhost on the browser I can neither get the index.html file nor see the images.

What I am trying to do is to display the image when I enter something as:

http://localhost/1.0.0/basemap/7/65/70.png
  • 7: folder indicating 7th zoom level
  • 65: folder indicating the latitude
  • 70.png: file indicating the longitude (folder 65 includes many png files)

What am I missing?


Solution

  • Ok, let me explain something, you already have a localhost server, which is defined inside a file called default that is the file that causes the "Welcome to nginx" or something to appear, and I believe you can't create a new server with the same server_name, let's remove that and make your localhost serve only those images,

    • First we need to delete the default file from sites-enabled , it will still exist inside sites-available if you ever want to get it back. ( note that all files inside sites-enabled are simply symlinks from the files inside sites-available )
    • We create a new file inside sites-available and call it whatever you want, images-app for example
    • create the new server inside the images-app file, I'll assume that the root of the app is inside a folder called /data of course you will map that to your own server structure.

      server {
          server_name localhost;
          root /data;
          index index.html;
          location / {
              try_files $uri =404;
          }
      }
      
    • now we go to sites-enabled and enable this site we created inside sites-available

      sudo ln -s /etc/nginx/sites-available/images-app /etc/nginx/sites-enabled/
      
    • make sure that all the nginx config are correct

      sudo nginx -t
      
    • If nothing is wrong we can go ahead and reload nginx settings

      sudo service nginx reload