Example of Nginx config with SSL


This is simple Nginx config with SSL and HSTS support. This is how every small website should look like under hood.

# Redirect www and non-www HTTP to HTTPS
server {
	listen 80;
	listen [::]:80;
	server_name www.nelebadnjak.com nelebadnjak.com;
	add_header X-Web-Node server1;
	rewrite ^(.*) https://www.nelebadnjak.com$1 permanent;
} 

# Redirect non-www HTTPS to www HTTPS
server {
	listen 443 ssl http2; # No need for HTTP2
	listen [::]:443 http2;
	server_name nelebadnjak.com;
	ssl on;
	ssl_certificate	/etc/letsencrypt/live/nelebadnjak.com/fullchain.pem;
	ssl_certificate_key   /etc/letsencrypt/live/nelebadnjak.com/privkey.pem;
	ssl_dhparam /etc/nginx/ssl/dhparam.pem;
	ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
	ssl_prefer_server_ciphers on;
	ssl_session_cache shared:SSL:10m;
	ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
	add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
	add_header X-xss-protection "1; mode=block" always;
	add_header X-frame-options "SAMEORIGIN" always;
	add_header X-Content-Type-Options "nosniff" always;
	add_header X-Web-Node server1;
	rewrite ^(.*) https://www.nelebadnjak.com$1 permanent;

}

# Handle www-HTTPS 
server {

	listen 443 ssl http2;
	listen [::]:443 http2;
	server_name www.nelebadnjak.com;
	access_log /var/log/nginx/access.log;
	error_log /var/log/nginx/error.log;
	root /home/nelebadnjak/www;
	index index.php index.html;
	ssl on;
	ssl_certificate	/etc/letsencrypt/live/nelebadnjak.com/fullchain.pem;
	ssl_certificate_key   /etc/letsencrypt/live/nelebadnjak.com/privkey.pem;
	ssl_dhparam /etc/nginx/ssl/dhparam.pem;
	ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
	ssl_prefer_server_ciphers on;
	ssl_session_cache shared:SSL:10m;
	ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
	add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
	add_header X-xss-protection "1; mode=block" always;
	add_header X-frame-options "SAMEORIGIN" always;
	add_header X-Content-Type-Options "nosniff" always;
	add_header X-Web-Node server1;

	# Caching static files
	location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc|js|css)$ {
		expires 1M;
		access_log off;
		add_header Cache-Control "public";
	}

	# Block access to all hidden files(dotfiles) ex: .git, .htaccess 
	location ~ /\. {
		deny all;
		access_log off;
 	}

	# Handle requests
	location / {
		try_files $uri $uri/ =404;
	}

	# pass to PHP7
	location ~ \.php$ {
		include snippets/fastcgi-php.conf;
		fastcgi_pass unix:/run/php/php7.0-fpm.sock;
	}


}