Nginx Production Laravel Server Configuration

Improving and securing your server is important for your Laravel application.

In this configuration we will:

  • Secure our server.
  • Hide server's sensitive information.
  • Disable access to hidden files.
  • Add custom errors to specific error codes.
  • Improve performance using compression.
server {
	server_tokens off;
	listen 443 ssl;
	listen [::]:443;
	server_name SERVERDOMAIN.COM;

	add_header X-Frame-Options "SAMEORIGIN";
	add_header X-XSS-Protection "1; mode=block";
	add_header X-Content-Type-Options "nosniff";
	add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";

	charset utf-8;

## Enable gzip compression
	gzip on;
	gzip_comp_level    5;
	gzip_min_length    256;
	gzip_proxied       any;
	gzip_vary          on;

	gzip_types
	application/atom+xml
	application/javascript
	application/json
	application/ld+json
	application/manifest+json
	application/rss+xml
	application/vnd.geo+json
	application/vnd.ms-fontobject
	application/x-font-ttf
	application/x-web-app-manifest+json
	application/xhtml+xml
	application/xml
	font/opentype
	image/bmp
	image/svg+xml
	image/x-icon
	text/cache-manifest
	text/css
	text/plain
	text/vcard
	text/vnd.rim.location.xloc
	text/vtt
	text/x-component
	text/x-cross-domain-policy;

## Post/File Size
	client_max_body_size 20M;

	root /home/web/www/current/public;

	index index.php;

	location / {
		try_files $uri $uri/ /index.php?$query_string;
	}

## Disable log for specific files.
	location = /favicon.ico { access_log off; log_not_found off; }
	location = /robots.txt  { access_log off; log_not_found off; }

	error_page 404 /index.php;

## Laravel script configuration using fpm 
	location ~ \.php$ {
		fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
		fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
		include fastcgi_params;
	}

## Disable access to hidden files.
	location ~ /\.(?!well-known).* {
		deny all;
	}

## SSL Certificate using Let's encrypt.
	ssl_certificate /etc/letsencrypt/live/SERVERDOMAIN.COM/fullchain.pem;
	ssl_certificate_key /etc/letsencrypt/live/SERVERDOMAIN.COM/privkey.pem;
	
}

server {
	listen 80;
	listen [::]:80;
	server_name SERVERDOMAIN.COM;
	return 301 https://$host$request_uri;
}

Victor Yoalli

This is me.