How To Install And Setup Nginx On Ubuntu

August 3, 2017
Install, nginx service, config file and domain handling.

Install

Install nginx using apt-get

sudo apt-get install nginx

Confirm if nginx is installed: http://localhost.

curl http://localhost

Nginx Welcome

You can use the following command to start/stop/restart nginx service.

sudo service nginx start
sudo service nginx stop
sudo service nginx restart

Nginx is automatically started during bootup.

Config file

Nginx config files are stored at /etc/nginx/sites-available/. The default confing file is named default. You need to use sudo to edit the config files.

cd /etc/nginx/sites-available/
sudo vi default

Below is the basic content of the nginx config file

server {
  listen   80; ## listen for ipv4; this line is default and implied

  # the html files are stored here
  root /usr/share/nginx/html;
  index index.html index.htm;

  location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ /index.html;
    # Uncomment to enable naxsi on this location
    # include /etc/nginx/naxsi.rules
  }
}

Configure nginx to handle domain request

Create config file

Duplicate a copy of default config and edit it.

cd /etc/nginx/sites-available
sudo cp default hello
sudo vi hello

Edit hello config file to change root and add server_name.

server {
  listen   80; ## listen for ipv4; this line is default and implied

  # the html files are stored here
  root /usr/share/nginx/hello;
  index index.html index.htm;

  # handle domain
  server_name www.mydomain.com;

  location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ /index.html;
    # Uncomment to enable naxsi on this location
    # include /etc/nginx/naxsi.rules
  }
}

Create content

Make sure to create the content for /usr/share/nginx/hello.

cd /usr/share/nginx/
sudo mkdir hello
cd hello
sudo vi index.html

Edit index.html at /usr/share/nginx/hello

<!DOCTYPE HTML>
<html lang="en-US">
  <head>
    <meta charset="UTF-8">
    <title>MyDomain</title>
  </head>
  <body>
    Hello
  </body>
</html>

Enable config

Enable the newly created hello config.

cd /etc/nginx/sites-enabled
sudo ln -s ../sites-available/hello

Restart nginx.

sudo service nginx restart
# Output
 * Restarting nginx nginx                                                [ OK ] 

You can view the page now: http://www.mydomain.com.

If you have yet to purchase the domain name or setup the DNS, you edit local host file (sudo vi /etc/hosts).

# remember to remove this later
127.0.0.1   www.mydomain.com

Check Log

For troubleshooting, you can check the nginx error log.

tail -f /var/log/nginx/error.log
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.