Operations 17 min read

Comprehensive Nginx Configuration Guide: Basics, Optimization, and Deployment

This article provides a step‑by‑step walkthrough of Nginx configuration, explaining the original nginx.conf structure, simplifying it, detailing global, events, and http blocks, and covering common optimizations such as history‑mode handling, reverse proxy setup, gzip compression, maintenance pages, multi‑site hosting, and essential command‑line operations.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Comprehensive Nginx Configuration Guide: Basics, Optimization, and Deployment

Introduction

The author, a self‑described architect who writes code and poetry, explains that understanding Nginx is essential for front‑end projects and aims to give a clear overall concept of its configuration.

Original nginx.conf Overview

The original configuration file is lengthy and confusing; the article first presents the full default file (including many commented lines) and then shows a cleaned‑up version with only 22 active lines.

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #             '$status $body_bytes_sent "$http_referer" '
    #             '"$http_user_agent" "$http_x_forwarded_for"';
    
    #access_log  logs/access.log  main;
    
    sendfile        on;
    #tcp_nopush     on;
    
    #keepalive_timeout  0;
    keepalive_timeout  65;
    
    #gzip  on;
    
    server {
        listen       80;
        server_name  localhost;
        
        location / {
            root   html;
            index  index.html index.htm;
        }
        
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

Simplified Configuration (Comments Removed)

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

Annotated Version

#nginx进程数,建议设置为等于CPU总核心数。
worker_processes  1;
# 事件区块开始
events {
    #单个进程最大连接数(最大连接数=连接数*进程数)
    #根据硬件调整,和前面工作进程配合起来用,尽量大,但是别把cpu跑到100%就行。
    worker_connections  1024;
}
#设定http服务器,利用它的反向代理功能提供负载均衡支持
http {
    #include:导入外部文件mime.types,将所有types提取为文件,然后导入到nginx配置文件中
    include       mime.types;
    #默认文件类型
    default_type  application/octet-stream;
    #开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件
    sendfile        on;
    #长连接超时时间,单位是秒
    keepalive_timeout  65;
    server {
        #提供服务的端口,默认80
        listen       80;
        #提供服务的域名主机名
        server_name  localhost;
        #对 "/" 启用反向代理,第一个location块开始
        location / {
            root   html;  #服务默认启动目录
            index  index.html index.htm;  #默认的首页文件,多个用空格分开
        }
        #错误页面路由
        error_page   500 502 503 504  /50x.html;  #出现对应的http状态码时,使用50x.html回应客户
        location = /50x.html {  #location区块开始,访问50x.html
            root   html;  #指定对应的站点目录为html
        }
    }
}

Overall Structure

The configuration can be divided into three logical parts:

Global block (settings before events )

events block (network connection handling)

http block (most server functionality, including server and location blocks)

Global Block

Sets overall server parameters such as user, worker processes, PID file, and log locations.

worker_processes  1;

This determines the number of worker processes and thus the concurrency capacity.

Events Block

Controls how Nginx handles network connections, e.g., maximum connections per worker.

worker_connections  1024;

HTTP Block

Contains most of the functional directives: MIME types, default content type, sendfile , keep‑alive timeout, and one or more server blocks.

Server Block

Defines a virtual host, its listening port, server name, and associated location blocks.

server {
    listen       80;
    server_name  localhost;
    location / {
        root   html;
        index  index.html index.htm;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

Location Block

Matches request URIs and defines how to serve static files or proxy to back‑ends.

Simple Deployment

For a basic website, only modify server_name and root to point to your site’s directory; Nginx will serve index.html from that folder.

Common Optimizations

1. Front‑end History Mode 404 Issue

location / {
    try_files $uri $uri/ /index.html;
}

This ensures that page refreshes on SPA routes fall back to index.html .

2. Reverse Proxy

Typical solution for cross‑origin requests:

#接口端
location /police/ {
    proxy_pass   http://192.168.1.182:8852/police/;
    proxy_redirect default;
    proxy_http_version 1.1;
    proxy_connect_timeout   60;
    proxy_send_timeout      60;
    proxy_read_timeout      90;
}

Requests beginning with /police are forwarded to the backend service.

3. Enable Gzip Compression

gzip on;  # default off
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
# optional advanced settings
gzip_static on;
gzip_proxied any;
gzip_vary on;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;

Compresses responses to reduce bandwidth and improve load speed.

4. Maintenance Page

# 系统临时维护请打开下面这行注释,并重启nginx,维护完毕后请注释下年这行,并重启nginx
# rewrite ^(.*)$ /maintainace.html break;

5. Multiple Sites on One IP

# 第一个网站:个人博客项目配置
server {
    listen       8080;
    root         /data/www/hexo;
    index        index.html;
    location / {
        try_files $uri $uri/ /index.html;
    }
}

# 第二个网站:直播网站项目配置
server {
    listen       8081;
    root         /data/www/geov;
    index        index.html;
    location / {}
}

Each server block represents a separate virtual host with its own port and document root.

6. Static/Dynamic Separation

location /image/ {
    root   /var/filecenter/;
}
location /static/ {
    root   /var/filecenter/;
}
location /car/ {
    root   /var/filecenter/;
}
location ~ .*(html|htm|gif|jpg|jpeg|bmp|png|ico|js|css)$ {
    root /Users/dalaoyang/Downloads/static;
}

Static assets are served directly by Nginx, while dynamic requests are proxied to backend services.

Basic Nginx Commands

# Install Nginx
yum install nginx

# Check if Nginx process exists
netstat -anput | grep nginx

# View listening ports
netstat -ntlp

# Start Nginx
nginx

# Reload configuration (graceful restart)
nginx -s reload

# Stop quickly
nginx -s stop

# Stop gracefully
nginx -s quit

# Test configuration file
nginx -t
Note: Changes to nginx.conf require a restart for them to take effect; updating static files in html does not.

References

https://blog.csdn.net/qq_44691484/article/details/126354702

https://juejin.cn/post/6844904144235413512

https://github.com/rui-rui-an/nginxpages

optimizationOperationsDeploymentconfigurationnginxReverse Proxy
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.