Sunday, November 16, 2014

Nginx Configuration and Server Blocks

Nginx (pronounced engine-x) it's a great piece of software. It isn't as popular as Apache, but it's a very capable solution for applications that need an efficient, high-performance reverse proxy or web server. Unlike Apache, Nginx is asynchronous, requiring very few or one thread to handle requests and doesn't require nearly as much overhead as a process-based server. We'll make sure to spend a few articles going over all of its features, but for now we'll just focus on the basic setup. And these articles aren't just for sysadmins. If you develop anything that will eventually need to be served somewhere, you should have this skill in your arsenal.

Prerequisites: Mac OS X or Linux Ubuntu 14.04.

Installation

Mac OS X

If you're on a mac, you're better off installing nginx through Homebrew. Head over to the Homebrew website and follow the installation instructions. Once that's completed, run brew install nginx

Linux Ubuntu 14.04

Run sudo apt-get install nginx

Configuration

These config steps are for Ubuntu, but if you're on a Mac, just replace all instances of /etc/nginx with wherever brew installs your nginx. Will most likely be located at /usr/local/etc/nginx

# remove the default symbolic link
sudo rm /etc/nginx/sites-enabled/default

# create and edit a new nginx configuration file
sudo vim /etc/nginx/sites-available/domain.com
# with the following contents
server {
    # listen on port 80
    listen 80;

    # for requests to these domains
    server_name domain.com www.domain.com;

    # keep logs in these files
    access_log /var/log/nginx/domain.com.access.log;
    error_log /var/log/nginx/domain.com.error.log;

    # Allow users to upload large files
    # See http://wiki.nginx.org/HttpCoreModule#client_max_body_size
    client_max_body_size 0;

    # example alias
    location / {
        alias /var/www/domain.com; # or wherever your site files are located
        try_files $uri $uri/ =404;
    }


    # example proxy pass
    #location / {
    #    proxy_pass http://localhost:9000;
    #    proxy_redirect off;

    #    proxy_read_timeout 5m;

    #    # make sure these HTTP headers are set properly
    #    proxy_set_header Host            $host;
    #    proxy_set_header X-Real-IP       $remote_addr;
    #    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    #}
}
# Make a symlink to your config file
sudo ln -s /etc/nginx/sites-available/domain.com /etc/nginx/sites-enabled/domain.com

sudo service nginx restart

# if you get errors run this
nginx -c /etc/nginx/nginx.conf -t

No comments:

Post a Comment