Home Useful Configs for NGINX
Post
Cancel

Useful Configs for NGINX

After posting the first of my linux SysAdmin quick config sample series titled “Useful Configs for squid” (which you can read here). I decided to write another post, this time about the powerful and popular web/cache server NGINX!

I spent quite some time reading through nginx official docs and other blogs/websites while testing each configuration directive in different scenarios. Some of the options presented in this post do not have good or any documentation. I hope you find them useful!

*** snippets are tested on nginx on Debian 8 (jessie) but they will work on other distros/OSs with minimal or no modification.

Disclaimer: These configuration files are meant to be small and simple and designed to help you get an idea of what is possible with NGINX or quickly test some of its capabilities in a lab environment. although they probably work but they may be far from complete at times. So It’s up to you to research further if you want to leverage nginx in production.


Connecting to PHP

Probably the first thing you want to do after installing nginx is to connect it to some php interpreter to be able to run your web application.

  • Install PHP (on debian : apt install php5 php5-fpm)
  • change NGINX config file like this (essentially only uncomment the relevant section):
1
2
3
4
5
6
7
8
location ~ \.php$ {
     include snippets/fastcgi-php.conf;

     # With php5-cgi alone:
     #fastcgi_pass 127.0.0.1:9000;
     # With php5-fpm:
     fastcgi_pass unix:/var/run/php5-fpm.sock;
}
  • add index.php to index line
  • verify socket properties in /etc/php5/fpm/pools.d/www.conf
    • socket permissions and user must be correct (they are correct in a default Debian Jessie install)

Redirect HTTP to HTTPS

There any many ways to accomplish this. Some websites advocate the use of if__($scheme … but THIS IS WRONG. it causes performance issues and also if in nginx behaves differently and you might get unexpected results. The correct way to do this is presented below, no rewrite, if , etc are needed this(see ):

1
2
3
location / {
    return 301 https://$server_name$request_uri;
}

*** Note that since we are doing a permanent redirect (301), it will be cached by browsers so it will be a one time thing and they will connect to https port by default in subsequent visits.

 

Nginx Reverse Proxy

Reverse proxy is a very popular and useful feature of nginx. It’s important that you completely understand how it works and how to use it effectively. a large number of websites and services are based on nginx reverse proxy like Netflix, CloudFlare CDN and many more!

basic reverse proxy:

1
2
3
4
5
6
7
server {
    listen 80;
    server_name rayanfam.com;
    location / {
        proxy_pass http://<IP of other web server>/[path of real website if not hosted on root];
    }
}

This feature is usually utilized minimally like this:

1
2
3
4
5
6
7
8
9
10
11
12
server {
    listen 80;
    server_name www.rayanfam.com devel.rayanfam.com rayanfam.com;

    location / {
        proxy_pass http://222.222.222.222:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

I suggest you read official docs on this feature at least, there are many good articles on reverse proxying with nginx on other websites too.

Forward Proxy

This is not a very used feature but for the sake of completeness and also because it is not available on other websites I will show you how to configure nginx as a forward proxy for your organization. It will do the job very well!

1
2
3
4
5
6
7
8
server {
	listen 80;
	server_name _;
	location / {
		resolver 8.8.8.8;
		proxy_pass http://$http_host$uri$is_args$args;
	}
}

*** Do not host this on a public facing IP!

IP-based Block

You may want to deny or allow access only from a specific ip range. you can achieve this with iptables, but this is an acceptable way too:

1
2
3
4
5
location / {
    allow 192.168.20.0/24;
    deny all;
    #... other directives
}

Custom Error Pages

You can easily customize your error page using nginx and setup fancy error pages for all types of error (GitHub is my favorite ^_^ ):

1
2
3
4
5
6
7
# Both are mandatory. error paged should be marked as internal

error_page 403 /forbidden.html;

location /forbidden.html {
    internal;
}

Log format and Destination

Changing the log format and log destination is trivial in nginx. I create a new access log format and then use it to log to syslog facility.

1
2
3
4
5
6
7
8
# creating log format
log_format mylogformat ‘$remote_addr $request

# log to a file using mylogformat
access_log /var/log/nginx/custom_access.log mylogformat;

# log to syslog server using mylogformat
access_log syslog:server=192.168.10.10 mylogformat;

you can view official nginx docs regarding field names for logs and support for syslog, etc.

Basic Caching with Nginx

This snippet is intended to give you a very rough idea of caching with nginx and the minimal configuration required to activate that. In a real server more sophisticated caching will probably be required but this will get you started on this topic.

*** Caching is one of the most advanced  features of nginx, make sure to study and understand it.

1
2
3
4
5
6
7
8
# First create the directory and set the required permissions#

proxy_cache_path /var/cache/nginx keys_zone=CACHE:10m;

server {
    proxy_cache CACHE;
    # ... other directives
}

HTTP Basic Authentication

It’s the simplest form of authentication you can have for your website or a single page. yet it is effective and secure (if your password is only known by you of course). BE CAREFUL not to put your password file in your web directory! (yes I’ve seen people do that)

1
2
3
4
5
6
7
run this command in your shell. It's not part of nginx config:
$ htpasswd -c /etc/nginx/.htpasswd shahriar

# nginx config → add in desired location block

    auth_basic "Private Content"; 
    auth_basic_user_file /etc/nginx/.htpasswd;

some links:

Official docs

Common config pitfalls (official docs)


I hope you found this blog post useful… spread the word and tell your friends! also do not hesitate to comment. Have fun sysadmin-ing!

This post is licensed under CC BY 4.0 by the author.

Assembly Challenge : Jump to a non-relative address without using registers

Introduction to systemd : Basic Usage and Concepts

Comments powered by Disqus.