Nginx Config For a Static Website
I noticed pagination was broken in production, but not locally when the site is
built. So after fixing it (it’s the try_files line), I decided to note down
the setup used.
Ideally, Cloudfare Pages would be better for a static site, but if you’d like to serve it in a linux box, then follow these steps.
- The site’s main nginx config file
/etc/nginx/conf.d/npras.in.conf:
server {
server_name npras.in;
# Remove trailing slash (redirect to non-trailing slash version)
rewrite ^/(.*)/$ /$1 permanent;
add_header X-Clacks-Overhead "GNU Terry Pratchett";
location / {
root /var/www/npras.in;
index index.html index.htm;
try_files $uri $uri.html $uri/index.html =404;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/npras.in/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/npras.in/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = npras.in) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
server_name npras.in;
return 404; # managed by Certbot
}
- This file is then referenced in nginx’s main config file:
/etc/nginx/nginx.conf. It’s included in thehttpblock. Only that’s relevant here:
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
gzip on;
types_hash_max_size 4096;
access_log logs/access.log;
# load server configs
include /etc/nginx/conf.d/npras.in.conf;
}
-
Ensure right access to the site’s directory
var/www/npras.inshould be chmodded to your user and group. Only then you’ll be able to push the files to the server via rsync. -
Know a few handy commands. Like
nginx -tto check if config changes are valid.nginx -s reloadto have the changes take effect.