Sub topic 3
Enabling HTTPS and redirecting HTTP
This chapter assumes you have Nginx installed and running, a server block for a domain, and sudo access. You should know what a TLS certificate is, and that HTTP uses port 80 while HTTPS uses port 443.
TLS (Transport Layer Security) is the protocol that encrypts traffic between a browser and your server. Nginx needs a certificate file and a matching private key. Keep the private key readable only by root.
Enabling HTTPS and redirecting HTTP
Use one server block to redirect port 80 and another to serve the site over port 443:
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
root /var/www/example.com/html;
}Test before reloading: sudo nginx -t && sudo systemctl reload nginx
Reading access and error logs
The access log records each request. The error log records problems. On Debian and Ubuntu, they are in /var/log/nginx/.
sudo tail -n 20 /var/log/nginx/error.log
sudo tail -n 20 /var/log/nginx/access.logTroubleshooting common problems
nginx -treports the file and line of a syntax error.- A 502 Bad Gateway means the upstream application is not running or not reachable.
- A 403 usually means file permissions block Nginx from reading the root directory.
- A 404 means the requested file does not exist under the root.
Load balancing with upstream groups
An upstream group lists backend servers. Nginx sends requests to them in round-robin order by default. Place the group in the http context, outside any server block:
upstream app_backend {
server 10.0.0.11:3000;
server 10.0.0.12:3000;
}Then point a location at it with proxy_pass http://app_backend;.
Tuning workers, compression, and caching
Set worker_processes in the main context, and enable compression in the http context. Caching uses proxy_cache_path and proxy_cache, which this chapter does not cover.
worker_processes auto;
http {
gzip on;
gzip_types text/css application/javascript application/json;
}Hardening and rate limiting
Hide the Nginx version and limit each client to about 10 requests per second on /login:
http {
server_tokens off;
limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;
server {
listen 80;
location /login {
limit_req zone=perip burst=20 nodelay;
}
}
}Exercise
Exercise
A browser requests http://example.com. Which server block handles the request, and what status code does the browser receive?
Show answer
The port 80 server block handles it. It returns 301 with a Location header pointing to https://example.com, so the browser repeats the request over HTTPS.