Mastering Nginx: Installation, Configuration, and Advanced Usage Guide
This comprehensive guide explains what Nginx is, its capabilities, step‑by‑step installation methods, core commands, configuration file structure, event‑driven model, global variables, authentication setup, virtual host configurations, and detailed location block usage for effective web server management.
What is Nginx?
NGINX is a free, open‑source, high‑performance HTTP server and reverse proxy, also supporting IMAP/POP3 proxy functions. It is known for high performance, stability, rich feature set, simple configuration, and low resource consumption.
What can Nginx do?
NGINX serves as a web server, reverse proxy, cache, load balancer, and media streaming server. It also works as an email proxy (IMAP, POP3, SMTP) and as a reverse proxy/load balancer for HTTP, TCP, and UDP traffic.
Nginx Installation Methods
Yum Installation
1. Install utils
yum install yum-utils
2. Configure yum repository
<code>vim /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key</code>3. Install Nginx
yum install nginxCompile Installation
1. Download and extract source
<code>wget http://nginx.org/download/nginx-1.9.4.tar.gz
tar -xzf nginx-1.9.4.tar.gz
cd nginx-1.9.4</code>2. Install build environment
<code>yum update
yum -y install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel</code>3. Compile and install
<code>groupadd www
useradd -g www www
./configure \
--user=www \
--group=www \
--prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-http_realip_module \
--with-threads
make
make install</code>4. Create symlink
ln -s /usr/local/nginx/sbin/nginx /usr/bin/nginx5. Start Nginx
nginx/sbin/nginxNginx Commands
nginx # start Nginx
nginx -t # test configuration syntax
nginx -s reopen # reopen logs (USR1)
nginx -s reload # reload configuration without restart (HUP)
nginx -s stop # force stop (TERM or INT)
nginx -s quit # graceful stop (QUIT)
Configuration File Structure
NGINX consists of modules controlled by directives in the configuration file. Directives are either simple (name and parameters ending with a semicolon) or block directives (enclosed in braces). Blocks such as
http,
server, and
locationform contexts. The
httpblock contains common directives for all sites, and can include multiple
serverblocks, each with its own
locationblocks.
<code>user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
...
}
http {
...
server {
...
location ... {
...
}
}
server {
...
}
}</code>Nginx Event‑Driven Model
Nginx operates on an event‑driven architecture. An event collector gathers events (from software, hardware, or users), an event sender forwards them to target objects, and an event processor handles read, write, and exception events.
Implementation of Event Processor
The event sender creates a process for each request and invokes the processor.
The event sender creates a thread for each request and invokes the processor.
The event sender queues the request and the processor handles it using non‑blocking I/O.
Nginx Event‑Driven Libraries
select – creates three descriptor sets for read, write, and exception events and uses the kernel’s
select()call, limited by the maximum file descriptor.
poll – creates a single set that can monitor all three event types simultaneously.
epoll – delegates descriptor list management to the kernel; the kernel notifies the process when events occur, avoiding full list polling.
Nginx Global Variables
$args – request line arguments (same as $query_string)
$content_length – value of the Content‑Length header
$content_type – value of the Content‑Type header
$document_root – value of the
rootdirective for the request
$host – request host header or server name
$http_user_agent – client User‑Agent string
$http_cookie – client cookies
$limit_rate – can limit connection speed
$request_method – HTTP method (GET, POST, etc.)
$remote_addr – client IP address
$remote_port – client port
$remote_user – username after basic auth
$request_filename – full file path derived from
rootor
alias$scheme – protocol (http or https)
$server_protocol – protocol version (e.g., HTTP/1.1)
$server_addr – server IP address
$server_name – server name
$server_port – port on which the request arrived
$request_uri – original URI with arguments
$uri – current URI without arguments
$document_uri – same as $uri
Nginx Access Authentication
The
auth_basicmodule provides HTTP Basic Authentication, but it transmits credentials in clear text, so it is not secure on its own.
Directive Explanation
auth_basic syntax :
auth_basic string | off;Default:
auth_basic off;Context: http, server, location, limit_except. The string appears in the authentication dialog.
auth_basic_user_file syntax :
auth_basic_user_file file;No default value. Context: http, server, location, limit_except. Specifies the file that stores usernames and passwords.
Creating Password File with htpasswd
htpasswd command syntax
<code>htpasswd [-cimBdpsDv] [-C cost] passwordfile username
htpasswd -b[cmBdpsDv] [-C cost] passwordfile username password
htpasswd -n[imBdps] [-C cost] username
htpasswd -nb[mBdps] [-C cost] username password</code>htpasswd parameters
<code>-c create password file
-n output encrypted content to screen; -m use MD5
-d use CRYPT
-p store password in plain text
-s use SHA
-b provide username and password on command line
-D delete a user from the file</code>Authentication Example
Configure Nginx to protect a Kibana instance:
<code>location /kibana/ {
auth_basic "kibana";
auth_basic_user_file /etc/nginx/kibanauser;
proxy_pass http://127.0.0.1:5601/;
proxy_set_header Host $host:5601;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
rewrite ^/kibana/(.*)$ /$1 break;
}</code>Generate the password file:
htpasswd -c /etc/nginx/kibanauser adminTest the authentication (screenshot below):
Nginx Virtual Host Configuration
1. Domain‑Based Virtual Hosts
Edit
/etc/nginx/nginx.conf:
<code>server {
listen 80 default_server;
server_name huazai.com;
location / {
root html/huazai;
index index.html;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
}
server {
listen 80;
server_name wanger.com;
location / {
root html/wanger;
index index.html;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
}</code>Create homepage files and reload Nginx:
<code>cd /usr/share/nginx/html/
mkdir wanger
mkdir huazai
echo "I'm huazai" >huazai/index.html
echo "I'm wanger" >wanger/index.html
chmod -R 777 wanger/
chmod -R 777 huazai/
nginx -s reload</code>Test:
<code>[root@wanger]# curl -xlocalhost:80 huazai.com
I'm huazai
[root@wanger]# curl -xlocalhost:80 wanger.com
I'm wanger</code>2. Port‑Based Virtual Hosts
Edit configuration:
<code>server {
listen 80 default_server;
server_name huazai.com;
location / {
root html/huazai;
index index.html;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
}
server {
listen 800;
server_name huazai.com;
location / {
root html/wanger;
index index.html;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
}</code>Test and restart:
<code>nginx -t
systemctl restart nginx</code>Access:
<code>[root@html]# curl 127.0.0.1:80
I'm huazai
[root@html]# curl 127.0.0.1:800
I'm wanger</code>Nginx Location Block Details
The
locationdirective selects configuration based on the request URI.
Location Syntax
<code>location [=|~|~*|^~|@] uri {
...
}</code>Matching Patterns and Order
Patterns can be plain strings or regular expressions. Modifiers:
=– exact match (highest priority)
^~– prefix match, stop further regex search
~– case‑sensitive regex
~*– case‑insensitive regex
@– named location for internal redirects
Matching order:
Exact match (=)
Prefix match with ^~ (longest)
Regex matches (~ and ~*)
Longest prefix match
Location Matching Examples
<code>location = / { return "Rule A"; }
location ^~ /static/ { return "Rule B"; }
location ^~ /static/files { return "Rule C"; }
location ~ .*(gif|jpg|png|js|css)$ { return "Rule D"; }
location ~* \.png$ { return "Rule E"; }
location /img { return "Rule F"; }
location / { return "Rule G"; }</code>Examples of which rule matches various URIs are described in the original text.
Location root vs alias
Both can be defined inside a
location.
rootappends the location value to the document root, while
aliasreplaces it.
<code>location /wanger {
root html;
index index.html;
}
# Request http://127.0.0.1/wanger/index.html serves /html/wanger/index.html
</code> <code>location /wanger {
alias html/;
index index.html;
}
# Request http://127.0.0.1/wanger/index.html serves /html/index.html
</code>Key differences:
aliasworks only inside
location, and must end with a slash;
rootcan be used in
http,
server, or
locationcontexts.
Ops Development Stories
Maintained by a like‑minded team, covering both operations and development. Topics span Linux ops, DevOps toolchain, Kubernetes containerization, monitoring, log collection, network security, and Python or Go development. Team members: Qiao Ke, wanger, Dong Ge, Su Xin, Hua Zai, Zheng Ge, Teacher Xia.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.