Boilerplate Nginx Config File

Published: 2024-06-29 | Updated: 2024-06-26
server {
 listen 80 default_server;
 listen [::]:80 default_server;

 server_name example.com;
 root /var/www/example.com;

 # Add index.php to the list if using PHP
 index index.html index.htm;

 charset utf-8;

 location / {
  # First attempt to serve request as file, then
  # as directory, then fall back to displaying a 404.
  try_files $uri $uri/ =404;
 }

 location ~* /favicon\.(ico|png|gif|jpg|jpeg|svg)$ {
  log_not_found off;
  access_log off;
 }


 location = /robots.txt {
  allow all;
  log_not_found off;
  access_log off;
 }

 # custom error pages
 error_page /404.html
 error_page 500 502 503 504 /custom_50x.html;

 # Gzip Settings
 gzip_static on;
 gzip on;

 # Set Cache TTL on Media: images, icons, video, audio, HTC
 location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|mp4|ogg|ogv|webm|htc)$ {
  # 30 days
  add_header Cache-Control "max-age=2592000";
  access_log off;
 }
 # Set Cache TTL on CSS and Javascript
 location ~* \.(?:css|js)$ {
  # 8 hours
  add_header Cache-Control "max-age=28800";
  access_log off;
 }

 # Redirect all traffic beginning with 'www' to domain-only
 server {
  server_name www.example.com;
  return 301 $scheme://example.com$request_uri;
 }

}