Tweaks for nginx web server

Some easy and nice to have tweaks for nginx web server.

Tweaks for nginx web server

Since I'm using nginx as a web server for Ghost, the information below is adapted to its config. But it is easily modifiable to whatever web server you are using.

Security Headers

Adding headers to increase the security of your site, protecting it from cross-site scripting attacks (XSS) should be on top of your things to add to nginx configuration, for your peace of mind.

I used this site to check how well I did implement the headers. At the beginning it was all red. Not that I expected it to be all fine from the start. After the test, you will have a table with the missing headers and their explanation. Take the time to read what each header does.

Initial check

So I proceeded with adding the missing headers in the configuration file related to my site.

Open the configuration file for your domain and in it go to the server - location. For myself, I had to add the following missing headers:

add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
add_header Content-Security-Policy "child-src 'self'";
add_header Referrer-Policy same-origin;
add_header Feature-Policy "vibrate 'self'; sync-xhr 'self' https://boratory.net";
Missing headers in nginx configuration

Now retest. This time you'll like the results.

After headers in place

Enable HTTP/2

Many people think of HTTP/2 as a shiny, superior successor to HTTP/1. I do not share this opinion, and here’s why. HTTP/2 is actually just another transport layer for HTTP/1, which isn’t bad because as a result, you can use HTTP/2 without having to change your application – it works with the same headers. You can just switch on HTTP/2 in NGINX and NGINX will gently handle all the protocol stuff for you. - Valentin Bartenev of NGINX

With this in mind, locate the listen variables associated with port 443 in your config file. The first one is for IPv6 connections and the second one is for all IPv4 connections. So why not enable HTTP/2 for both since you're here.

listen [::]:443 ssl http2 ipv6only=on;
listen 443 http2 ssl;
Tell Nginx to use HTTP/2 with supported browsers

Now that you edited your config, it's a good time to check it before restarting nginx. For that, you have to run

sudo nginx -t
Check yourself before you break yourself

If everything's ok, reload nginx web server with the following command:

sudo /etc/init.d/nginx reload
Restart nginx, you're done

To test your work, use the https://http2.pro/ web site. You should see this result:

Yay! Job well done!