Configuring Nginx Server Blocks
In Nginx, a Server Block (equivalent to a Virtual Host in Apache) allows you to host
multiple websites on a single server. Each site requires its own configuration file containing specific
directives for that domain.
1. The Nginx Architecture
Nginx uses a specific directory structure to manage configurations. You create your configuration in
sites-available and then "enable" it by creating a symbolic link to sites-enabled.
Configuration Workflow
/etc/nginx/
sites-available/
(Actual File Created Here)
➔
➔
/etc/nginx/
sites-enabled/
(Read by nginx.conf)
2. Creating the Server Block
First, navigate to the available sites directory and create a file named after your domain (e.g.,
example.com.conf).
cd /etc/nginx/sites-available/
sudo nano example.com.conf
The Configuration Structure
Below is a professional configuration for a WordPress site (PHP). This configuration includes standard
directives, PHP processing, and custom logging.
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/public_html;
index index.php;
access_log /var/log/nginx/access_example.com.log combined buffer=256k
flush=60m;
error_log /var/log/nginx/error_example.com.log;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
include /etc/nginx/includes/fastcgi_optimize.conf;
}
include /etc/nginx/includes/browser_caching.conf;
}
3. Enabling the Site
Once the file is created, you must create a symbolic link (symlink) to the sites-enabled
directory. This tells Nginx to treat this site as active.
sudo ln -s /etc/nginx/sites-available/example.com.conf
/etc/nginx/sites-enabled/example.com.conf
4. Testing and Reloading
Before applying changes, always test the syntax to prevent the web server from crashing due to a typo.
sudo nginx -t
If the test returns successful, reload Nginx.
⚠️ Important: Reload vs. Restart
Always use
reload instead of
restart when applying configuration changes.
- Reload: Keeps the server running. If there is an error, it aborts the reload and
keeps the old configuration active.
- Restart: Stops the server completely. If there is an error, the server will stay
dead until you fix it.
sudo systemctl reload nginx
5. Optimization Includes (Optional)
For cleaner code, you can create separate files for caching and FastCGI optimization and include them in your
server block.
Example: Browser Caching
File: /etc/nginx/includes/browser_caching.conf
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
access_log off;
}