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)
Symbolic Link
(Shortcut)
/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 { # 1. Port Configuration listen 80; # 2. Domain Name server_name example.com www.example.com; # 3. Root Directory & Index Files root /var/www/example.com/public_html; index index.php; # 4. Logging (Specific to this site) access_log /var/log/nginx/access_example.com.log combined buffer=256k flush=60m; error_log /var/log/nginx/error_example.com.log; # 5. WordPress Permalinks (Try Files) location / { try_files $uri $uri/ /index.php$is_args$args; } # 6. PHP Processing location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php8.3-fpm.sock; # Optional: Include optimization settings include /etc/nginx/includes/fastcgi_optimize.conf; } # 7. Browser Caching (Optional Include) 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.
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; }