Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Essential Nginx Configuration Recipes for Web Servers

Tech May 8 16

Virtual Host Setup

Each server block in Nginx represents a virtual host. Valid configurations include same port/different domain or same domain/different port.

Nginx’s default main configuration includes all .conf files under conf.d via include /usr/local/nginx/conf.d/*.conf;. Create a new file there named by port or domain for clarity, e.g., file-proxy.conf for a port 80, file-demo.technexus.com host:

server {
    listen 80;
    server_name file-demo.technexus.com;
    root /usr/local/nginx/htdocs/file-share;
    index index.html index.htm;
    access_log /var/log/nginx/file-demo_access.log combined;
    error_log /var/log/nginx/file-demo_error.log warn;
}

HTTP Basic Authentication

Use this for restricting access to private endpoints, such as internal file shares. Nginx requires hashed credentials via htpasswd from httpd-tools.

  1. Install dependencies:
dnf install -y httpd-tools
  1. Initialize a password file with user maria (use -c only for first creation):
htpasswd -Bc /usr/local/nginx/secret-credentials maria
  1. Add user leo without overwriting the file:
htpasswd -B /usr/local/nginx/secret-credentials leo

Add authentication directives to http, server, or location blocks:

server {
    listen 80;
    server_name private-dashboard.technexus.com;
    auth_basic "Restricted Access: Enter Credentials";
    auth_basic_user_file /usr/local/nginx/secret-credentials;

    location / {
        root /usr/local/nginx/htdocs/dashboard;
        index dashboard.html;
    }
}

PHP-FPM Integration

Nginx natively serves static HTML; pass .php requests to PHP-FPM via FastCGI. Prefer Unix sockets over TCP for local connections to reduce overhead.

server {
    listen 80;
    server_name php-app.technexus.com;
    root /usr/local/nginx/htdocs/php-app;
    index index.php index.html;

    location ~ \.php$ {
        # Replace 127.0.0.1:9000 with unix:/var/run/php-fpm/php-fpm.sock if using sockets
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;

        # Optional FastCGI tuning
        fastcgi_cache_path /usr/local/nginx/fcgi_cache levels=1:2 keys_zone=PHP_CACHE:15m inactive=8m;
        fastcgi_cache PHP_CACHE;
        fastcgi_cache_valid 200 302 45m;
        fastcgi_cache_valid 301 1d;
        fastcgi_cache_valid any 2m;
        fastcgi_connect_timeout 25;
        fastcgi_send_timeout 25;
        fastcgi_read_timeout 25;
        fastcgi_buffer_size 32k;
        fastcgi_buffers 8 32k;
    }
}

PATH_INFO Support

PHP uses PATH_INFO for routing clean URLs like /tools.php/login/dashboard. Nginx’s default regex blocks this. Two workarounds exist:

Internal PHP Parsing

location ~ \.php {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_script_name;
}

Nginx Regex Parsing

More secure, for Nginx ≥0.7.31:

location ~ \.php {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    include fastcgi_params;

    set $script_path $fastcgi_script_name;
    set $path_info "";
    if ($fastcgi_script_name ~ "^(.+?\.php)(/.*)$") {
        set $script_path $1;
        set $path_info $2;
    }

    fastcgi_param SCRIPT_FILENAME $document_root$script_path;
    fastcgi_param SCRIPT_NAME $script_path;
    fastcgi_param PATH_INFO $path_info;
}

URI Rewriting

Use rewrite to redirect or modify URIs. Flags control behavior: last restarts location matching, break stops it, permanent (301) and redirect (302) send HTTP redirects.

Page-to-Page Redirect

server {
    listen 80;
    server_name docs.technexus.com;
    root /usr/local/nginx/htdocs/docs;

    location / {
        rewrite ^/v1/guide.html$ /v2/quickstart.html permanent;
        index index.html;
    }
}

Full Domain Redirect

server {
    listen 80;
    server_name old-site.technexus.com;
    rewrite ^/(.*)$ https://new-site.technexus.com/$1 permanent;
}

Forward Proxy

For internal clients to access external networks. Requires DNS resolvers.

server {
    listen 3128;
    access_log /var/log/nginx/forward-proxy_access.log;

    location / {
        resolver 8.8.8.8 8.8.4.4 valid=300s;
        resolver_timeout 10s;
        proxy_pass http://$http_host$request_uri;
        proxy_set_header Host $http_host;
    }
}

Reverse Proxy & Load Balancing

Reverse proxies cache content, handle SSL, and distribute traffic. Load balancing pools (upstream) define backend servers.

Basic Reverse Proxy

server {
    listen 80;
    server_name app.technexus.com;

    location / {
        proxy_pass http://192.168.1.45:8080;
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Accept-Encoding "";
        proxy_buffering off;
    }
}

WebSocket Proxy

Upgrade HTTP/1.1 connections to WebSocket:

upstream ws_backend {
    server 192.168.1.50:8081;
}

server {
    listen 8081;
    server_name ws.technexus.com;

    location / {
        proxy_pass http://ws_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

Load Balancing

Round Robin (Default)

upstream app_pool {
    server 192.168.1.45:8080;
    server 192.168.1.46:8080;
    server 192.168.1.47:8080 backup;
    server 192.168.1.48:8080 down;
}

server {
    listen 80;
    server_name app.technexus.com;
    location / {
        proxy_pass http://app_pool;
        proxy_set_header Host $host;
    }
}

Weighted Round Robin

upstream app_pool {
    server 192.168.1.45:8080 weight=3;
    server 192.168.1.46:8080 weight=1;
}

IP Hash

Fixes clients to one backend for session persistence:

upstream app_pool {
    ip_hash;
    server 192.168.1.45:8080;
    server 192.168.1.46:8080;
}

HTTPS Configuration

Use TLS for secure communication. Generate self-signed certificates for testing; use trusted CAs for production.

  1. Generate self-signed certs:
cd /usr/local/nginx/conf
openssl genrsa -out tls.key 2048
openssl req -new -x509 -key tls.key -out tls.crt -days 365 -subj "/C=US/ST=California/L=San Francisco/O=TechNexus/CN=*.technexus.com"
  1. HTTPS-only server with HSTS:
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name app.technexus.com;

    ssl_certificate /usr/local/nginx/conf/tls.crt;
    ssl_certificate_key /usr/local/nginx/conf/tls.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5:!RC4;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1h;
    ssl_stapling on;
    ssl_stapling_verify on;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    root /usr/local/nginx/htdocs/app;
    index index.html;
}
  1. HTTP to HTTPS redirect:
server {
    listen 80;
    listen [::]:80;
    server_name app.technexus.com;
    return 301 https://$host$request_uri;
}

Proxy Caching

Cache backend responses to reduce load and improve latency.

proxy_cache_path /var/cache/nginx/proxy levels=1:2 keys_zone=APP_CACHE:20m max_size=20g inactive=12m use_temp_path=off;

server {
    listen 80;
    server_name app.technexus.com;

    location / {
        proxy_cache APP_CACHE;
        proxy_cache_revalidate on;
        proxy_cache_min_uses 2;
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
        proxy_cache_lock on;
        add_header X-Cache-Status $upstream_cache_status;
        proxy_pass http://app_pool;
    }
}

try_files for Clean URLs (Pseudostatic)

Map clean URLs to dynamic backends or static fallback resources.

PHP Application

server {
    listen 80;
    server_name blog.technexus.com;
    root /usr/local/nginx/htdocs/blog;
    index index.php;

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

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Reverse Proxy Falblack

server {
    listen 80;
    server_name media.technexus.com;
    root /usr/local/nginx/htdocs/media;

    location ~* \.(jpg|jpeg|png|gif|webp)$ {
        try_files $uri @media_backup;
    }

    location @media_backup {
        proxy_pass http://192.168.1.60:8080;
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Comprehensive Guide to Hive SQL Syntax and Operations

This article provides a detailed walkthrough of Hive SQL, categorizing its features and syntax for practical use. Hive SQL is segmented into the following categories: DDL Statements: Operations on...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.