Nginx standard configuration

Here is a Nginx standard configuration that supports multi sites and php-fpm.

Make directories

$ sudo mkdir /etc/nginx/global
$ sudo mkdir /etc/nginx/sites-available
$ sudo mkdir /etc/nginx/sites-enable

Configure Nginx

Edit /etc/nginx/nginx.conf

$ sudo vi /etc/nginx/nginx.conf
# Generic startup file.
user http;
 
# usually equal to number of CPUs you have. run command 
# "grep processor /proc/cpuinfo | wc -l" to find it
worker_processes  auto;
worker_cpu_affinity auto;

access_log /var/log/nginx/access.log;
error_log  /var/log/nginx/error.log;
#pid        /run/nginx.pid;
 
# Keeps the logs free of messages about not being able to bind().
#daemon     off;
 
events {
    worker_connections  1024;
}
 
http {
#   rewrite_log on;
 
    include mime.types;
    default_type       application/octet-stream;
    sendfile           on;
#   tcp_nopush         on;
    keepalive_timeout  3;
#   tcp_nodelay        on;
    gzip               on;
    # php max upload limit cannot be larger than this size     
#   client_max_body_size 5G;
    index              index.html index.htm index.php;
 
    include sites-enabled/*;
}

Edit restriction.conf

$ sudo vi /etc/nginx/global/restriction.conf
# Global restrictions configuration file.
# Designed to be included in any server {} block.
location = /favicon.ico {
	log_not_found off;
	access_log off;
}

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

# Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
# If this option is enabled, nextcloud can only upload up to 20MiB.
#location ~ /\. {
#	deny all;
#	access_log off;
#	log_not_found off;
#}

Add site specific configuration file

$ sudo vim /etc/nginx/sites-available/www.example.com.conf
server {
    server_name www.example.com;
    root /srv/http/www.example.com;
    index index.html index.htm index.php;

    listen 80;
    listen [0::0]:80;

    gzip on;

    access_log /var/log/nginx/www.example.com.access.log;
    error_log /var/log/nginx/www.example.com.error.log;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_intercept_errors on;
        fastcgi_pass unix:/run/php-fpm/php-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    location ~* .(?:css|js) {
        add_header Cache-Controle "public, max-age:31536000";
    }
}

Enable site specific configuration

$ sudo ln -s /etc/nginx/sites-available/www.example.conf /etc/nginx/sites-enabled/www.example.conf

Check the configuration

$ sudo nginx -t

Restart Nginx

$ sudo systemctl restart nginx

Last Updated on September 16, 2024 by Kenn


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *