Useful Nginx Configuration

The way the Nginx web server works is determined by its configuration files. If running a PHP application, some useful Nginx configuration code snippets can be seen below.

To route all requests through through an index.php file.

location / {
    try_files $uri $uri/ /index.php?$args;
}

If running a live application, you may wish to redirect users to the www subdomain and possibly using https, should you have a valid SSL certificate installed.

Nginx may provide a default-ssl.conf that contains the SSL configuration. The redirect can be added within this file, or within your default HTTPS block.

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /srv/www/example.com/keys/ssl.crt;
    ssl_certificate_key /srv/www/example.com/keys/www.example.com.key;
    return 301 https://www.example.com$request_uri;
}

Gzip compression compresses your web pages and stylesheets before sending them over to the browser, which improves page speed performance.

Enabling Gzip compression can be done by adding the following code.

gzip on;
gzip_disable "msie6";

gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

Leveraging browser caching so that your static resources are cached in the user’s browser can aid website performance.

server {
    listen       80;
    server_name  example.com;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 365d;
    }

    location ~*  \.(pdf)$ {
        expires 30d;
    }
}

If you would rather password protect the website, this can be achieved by creating a .htpasswd file on the server, preferably outside of the document root, and adding the following configuration:

location / {
    auth_basic "Restricted Content";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

The .htpasswd contains the username and the hashed password on a single line. It might look similar to the below.

admin:$apr1$xo.YhGaq$ifuFi9Rz25njt43ICElN3R2Cos.

You can also deny access to particular files, such as the .htaccess and .gitignore files.

location ~ /\.(ht|gitignore) {
    deny all;
}

This will ensure that a 403 error code is returned if a user tries to access the files.

You can also use similar syntax to protect directories. For example, to protect dir1, dir2 and dir3 directories:

location ~ /(dir1|dir2|dir3) {
   deny all;
}

To configure custom error pages, use the error_page directive, followed by the error code and the link to the page.

error_page 404 /custom_404.html;
location = /custom_404.html {
    root /usr/share/nginx/html;
    internal;
}

error_page 500 502 503 504 /custom_50x.html;
location = /custom_50x.html {
    root /usr/share/nginx/html;
    internal;
}