Nginx Configuration File Locations: The location of Nginx configuration files varies depending on the installation method.
Source Code Compilation: Typically found in /usr/local/nginx/conf directory.
Yum Installation: Usually in /etc/nginx/ directory (main configuration file) and /etc/nginx/conf.d directory.
Docker Container: Generally located in /etc/nginx directory.
Nginx Main Configuraton Optimization
# Change worker user to root to avoid permission issues
user root;
# Defines the number of worker processes for handling client connections
worker_processes auto;
# Configure maximum number of open files for worker processes
worker_rlimit_nofile 65535;
# Nginx error log path with warn level
error_log /var/log/nginx/error.log warn;
# Nginx PID file path
pid /var/run/nginx.pid;
# Concurrency optimization
events {
# Sets the maximum number of simultaneous connections per worker process
worker_connections 65535;
# Enables accepting multiple connections at once
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Define a custom log format
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# HTTP access log path with custom format
access_log /var/log/nginx/access.log main;
# Enable sendfile for efficient file transfers
sendfile on;
# Enable TCP_NOPUSH for sending full packets
tcp_nopush on;
# Disable TCP_NODELAY for small packet optimization
tcp_nodelay on;
# Keep-alive timeout configuration
keepalive_timeout 60s;
# Client request size limits
client_max_body_size 20m;
# Timeout for reading request headers
client_header_timeout 60s;
# Timeout for reading request body
client_body_timeout 60s;
# Enable gzip compression
gzip on;
# Configure gzip buffers
gzip_buffers 16 8k;
# Set gzip compression level (1-9)
gzip_comp_level 6;
# Disable gzip for old IE browsers
gzip_disable 'MSIE [1-6].';
# Minimum HTTP version for gzip
gzip_http_version 1.0;
# Minimum response length for compression
gzip_min_length 1k;
# File types to compress
gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png image/tiff image/x-ms-bmp;
gzip_vary off;
# FastCGI optimization parameters
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
# Hide Nginx version information for security
server_tokens off;
# Include additional configuration files
include /etc/nginx/conf.d/*.conf;
server {
listen 80;
server_name example.com;
# Redirect HTTP to HTTPS
rewrite ^(.*) https://$server_name$1 permanent;
}
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.pem;
ssl_certificate_key /etc/ssl/private/example.com.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
access_log /var/log/nginx/example.com_access.log main;
error_log /var/log/nginx/example.com_error.log warn;
# Static file serving
location / {
root /var/www/html;
index index.html;
}
location /static/ {
alias /var/www/html/static/;
index index.html;
}
# Dynamic requests proxy
location /api/ {
proxy_redirect off;
proxy_set_header Host api.service.com;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://192.168.1.100:8080/;
}
# Cache common image formats
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|svg|webm)$ {
expires 1h;
}
}
}
HTTP to HTTPS Redirection
server {
listen 80;
server_name example.com;
rewrite ^(.*) https://$server_name$1 permanent;
}
Nginx Proxy for PHP Services
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.pem;
ssl_certificate_key /etc/ssl/private/example.com.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
index index.html index.php;
root /var/www/html/app/web;
rewrite (\/\.svn|.git\/) /404/;
if ($http_user_agent ~* yahoo|bingbot) {
return 403;
}
if ($query_string ~* ".*(insert|select|delete|update|count|master|truncate|declare|'|%27|%22|%3C|%3E|;|%20and%20|%20or%20).*"){
return 404;
}
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ .*\.(php|php5)?$
{
fastcgi_pass 127.0.0.1:9000;
fastcgi_param ENV 'prod';
fastcgi_index index.php;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)?$
{
expires 1h;
}
# Logging
access_log off;
}
Nginx as a Proxy Server
Nginx serves as an excellent high-performance proxy server, supporting both forward and reverse proxy configurations.
Forward Proxy
In a forward proxy setup, Nginx acts on behalf of the client to access target servers.
server{
resolver 8.8.8.8;
listen 80;
location / {
proxy_pass http://$http_host$request_uri;
}
}
Configure the http_proxy environment variable on the client: export http_proxy=http://your_proxy_server:port to use the proxy for internet access.
With this setup, when accessing websites like Baidu, the website only sees the Nginx server's IP, not the client's real IP.
Reverse Proxy
Clients access Nginx directly without knowing about the backend services.
server {
listen 80;
server_name example.com;
location / {
proxy_set_header Host example.com;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass https://backend.example.com/;
}
}
Nginx as a Load Balancer
Nginx can function as an efficient HTTP load balancer, distributing traffic across multiple application servers to enhance web application performance, scalability, and reliability.
upstream backend_servers {
server 192.168.1.201;
server 192.168.1.202;
}
server {
listen 80;
location / {
proxy_pass http://backend_servers;
}
}
This configuration enables round-robin load balancing across the two backend servers.
Load Balancer Parameters
backup - Mark server as backup. Used when primary servers are unavailable.
down - Mark server as permanently unavailable
fail_timeout=time - Consider server unavailable after specified failed attempts
max_conns=number - Limit maximum active connections to server
max_fails=number - Set maximum failed connection attempts
weight=number - Set server weight (default: 1)
Weighted distribution example:
upstream backend_servers {
server 192.168.1.201 weight=2;
server 192.168.1.202 weight=1;
}
server {
listen 80;
location / {
proxy_pass http://backend_servers;
}
}
Common Load Balancing Strategies:
Round Robin (default):
upstream backend {
server 127.0.0.1:3000;
server 127.0.0.1:3001;
}
Weighted Distribution:
upstream backend {
server 127.0.0.1:3000 weight=2;
server 127.0.0.1:3001 weight=1;
}
Backup Server:
upstream backend {
server 127.0.0.1:3000 backup;
server 127.0.0.1:3001;
}
IP Hash (session persistence):
upstream backend {
ip_hash;
server 127.0.0.1:3000;
server 127.0.0.1:3001;
}
Least Connections:
upstream backend {
least_conn;
server 127.0.0.1:3000;
server 127.0.0.1:3001;
}
Nginx as a Static File Server
Nginx efficiently serves static content like HTML pages, images, and files from different directories based on requests.
server {
listen 80;
server_name 127.0.0.1;
location / {
root /var/www/static;
index index.html index.htm;
}
location /images/ {
root /var/www;
}
location /files/ {
root /var/www;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /var/www/static;
}
}
Nginx Reverse Proxy for WebSocket Services
server {
listen 443 ssl;
server_name ws.example.com;
ssl_certificate /etc/ssl/certs/ws.example.com.pem;
ssl_certificate_key /etc/ssl/private/ws.example.com.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://10.0.0.5:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
Nginx Reverse Proxy Example
# HTTP to HTTPS redirection method 1
server {
listen 80;
server_name example.com;
rewrite ^ https://$http_host$request_uri? permanent;
}
# HTTP to HTTPS redirection method 2
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name app.example.com;
root /usr/share/nginx/html;
if ($host = "app.example.com") {
rewrite ^/(.*)$ https://app.example.com permanent;
}
location / {
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
# HTTPS proxy configuration
server {
listen 443 ssl;
server_name app.example.com;
ssl_certificate /etc/ssl/certs/app.example.com.pem;
ssl_certificate_key /etc/ssl/private/app.example.com.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
proxy_set_header Host app.example.com;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://10.1.1.100:8080/;
}
}
Nginx Subdirectory Deployment for React Project
location ^~ /app/ {
# Application directory
alias /var/www/react/app/;
# Fix 404 on refresh
try_files $uri $uri/ /app/index.html;
index index.html;
access_log /var/log/nginx/access/app.example.com.log main;
error_log /var/log/nginx/app.example.com.log warn;
}
Nginx Gzip Compression Configuration
gzip on; # Enable Gzip compression
gzip_min_length 1k; # Minimum file size for compression
gzip_buffers 4 16k; # Compression buffer settings
gzip_http_version 1.0; # HTTP version compatibility
gzip_comp_level 6; # Compression level (1-9)
# MIME types to compress
gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary on; # Add Vary header
Nginx CORS Solution
location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
}
Nginx IP Black/White List Configuration
IP access control can be applied at any Nginx configuration block level.
deny 192.168.1.66;
allow 192.168.1.0/24;
allow 10.1.20.0/16;
allow 34.26.157.0/24;
deny all;
This configuration:
- Allows the 192.168.1.0/24 network except 192.168.1.66
- Allows the 10.1.20.0/16 network
- Allows the 34.26.157.0/24 network
- Denies all other IP addresses
Nginx SSL Certificate Configuration
server {
listen 443 ssl;
server_name api.example.com;
ssl_certificate /etc/ssl/certs/api.example.com.pem;
ssl_certificate_key /etc/ssl/private/api.example.com.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root /var/www/api;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /var/www/api;
}
}
Nginx Static and Dynamic Separation
The principle of static/dynamic separation involves Nginx directing requests to different servers based on their type.
# Dynamic content (PHP, JSP, CGI) goes to application server
location ~ .*\.(php|jsp|cgi)?$
{
proxy_pass http://app_server;
}
# Static content (HTML, CSS, JS, images) served directly
location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$
{
root /data/www/static;
# Browser cache for 3 days
expires 3d;
}
Nginx Implicit Redirection (Browser URL Preservation)
Redirect https://old.example.com to https://new.example.com while preserving the original URL in the browser.
server {
listen 80;
listen 443 ssl;
server_name old.example.com;
access_log /var/log/nginx/old.example.com-access.log main;
error_log /var/log/nginx/old.example.com-error.log;
ssl_certificate /etc/ssl/certs/old.example.com.pem;
ssl_certificate_key /etc/ssl/private/old.example.com.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location ~* / {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass https://new.example.com;
}
}
server {
listen 443 ssl;
server_name api.example.com;
ssl_certificate /etc/ssl/certs/api.example.com.pem;
ssl_certificate_key /etc/ssl/private/api.example.com.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
access_log logs/access_api.log main;
error_log logs/error_api.log error;
location / {
rewrite ^.+api/?(.*)$ /$1 break;
proxy_pass https://api.service.com/;
}
}