Nginx QuickStart – Serve Static Files

Documenting my journey of discovery of Nginx – the coolest open source web/reverse proxy server on the planet.

INSTALL NGINX ON UBUNTU:
To install nginx on Ubuntu simply run:

$ sudo apt-get install nginx


START SERVICE:
To start the nginx service:

$ sudo service nginx start


CHECK RUNNING PROCESSES:
Open System Monitor and check to determine that you have atleast 1 process named “nginx” and atleast 1 process running as “nginx: worker process” (I’ll explain later about the relevance of number of worker processes spawned and their relationship to the configuration file). See example screenshot below:

image


CONFIGURE NGINX FOR STATIC FILES:
To configure nginx to serve static files (a .jpg image and .html file in our example), browse to the directory /etc/nginx and first make a backup copy of the nginx configuration file titled nginx.conf. Then paste the below configuration settings and save the file:


user www-data;
worker_processes 4;
pid /run/nginx.pid;
events 
{  
    worker_connections 768;
}
http {
  server {
    location / {
      root /data/www;
    }

    location /images/ {
      root /data;
    }
  }
}

CREATE DIRECTORIES THAT HOLD CONTENT TO BE SERVED OUT VIA NGINX:

  • Create 2 new directories at /data/www and /data/images
  • Then change recursive ownership of the /data directory to the www-data account as defined in the user “directive” of the nginx.conf file described above by running the following command:
$ sudo chown -R www-data:www-data /data


CREATE STATIC FILES TO BE SERVED OUT VIA NGINX:

  • Create an image called hello.jpg in the /data/images directory. You can also save the below sample image to /data/images if you prefer 
  • Create a .html file called index.html in /data/www. Copy and paste the below HTML code

hello.jpg

image

index.html

<html>
<body>
	<h1>This text is rendered from index.html</h1>
	<img src ="/images/hello.jpg">
</body>
</html>


RELOAD THE NEW NGINX CONFIGURATION:

$ sudo service nginx reload


TEST THAT NGINX WORKS:

Browse to http://127.0.0.1/images/hello.jpg and check that your image has loaded as shown below

image

Browse to http://127.0.0.1/index.html and check that your static page has loaded as shown below

image
Advertisements