An Overview and Setup Guide for Nginx
Introduction to Nginx
Nginx stands out as a high-performance HTTP and reverse proxy web server, also functioning as an IMAP/POP3/SMTP proxy server. Developed by Igor Sysoev, it was originally intended to deliver efficient and stable services for the Rambler.ru website. Nginx has gained widespread recognition for its reliability, extensive feature set, straightforward configuration syntax, and minimal system resource consumption.
Key Features
- Cross-platform Compatibility: Nginx can run on most Unix-like operating systems and offers a Windows port, ensuring broad compatibility.
- Simple Configuraton: The configuration style resembles programming practices, making it intuitive for users to set up.
- Non-blocking High Concurrency: Utilizing the latest epoll model, Nginx supports up to 50,000 concurrent connections, performing well under real-world production loads with typical handling of 20,000–30,000 connections.
- Event-driven Architecture: Communication relies on the epoll model, enabling robust concurrent connection support.
- Master/Worker Design: A master process spawns one or more worker processes, enhancing processing efficiency.
- Low Memory Usage: Efficient memory utilization during high-concurrency request handling.
- Bandwidth Conservation: Offers GZIP compression and browser caching headers to optimize bandwidth usage.
Pros and Cons
Advantages:
- High Performance: Built on an event-driven architecture, Nginx excels at managing large numbers of concurrent connections, ideal for high-load scenarios. Its asynchronous non-blocking approach boosts throughput by eliminating wait times for requests.
- Reliability: As a high-performance HTTP and reverse proxy server, along with being an IMAP/POP3/SMTP proxy, Nginx ensures high availability and scalability, widely used in major websites and applications.
- Easy Configuration: The configuration file is clear and easy to understand and modify. It supports various syntaxes like location-based, domain-based, and regex-based configurations, allowing flexible customization.
- Modular Design: Modular structure allows for rich modules and plugin ecosystems, extending functionality and performance according to diverse needs.
- Hot Deployement Support: Allows updates to configuration files or version upgrades without stopping the service, facilitating maintenance and deployment.
- Minimal Memory Footprint: Low memory consumption during highh-concurrency tasks, enabling better performance within limited resources.
Disadvantages:
- Protocol Limitation: Supports only HTTP, HTTPS, and email protocols, excluding others like FTP, which restricts its use cases.
- Limited Dynamic Handling: While capable of communicating with backend servers via FastCGI, its dynamic processing capability lags behind specialized application servers like Tomcat or Resin.
- Difficult Debugging: Error logs are relatively basic, potentially complicating troubleshooting of complex issues.
- Learning Curve: Although configuration files are straightforward, understanding how Nginx works internally requires time and experience.
- Limited Control Features: Compared to dedicated web application firewalls or load balancers, Nginx provides fewer built-in controls for access management and security policies.
Note that these points reflect general characteristics and common applications of Nginx. Actual suitability depends on specific project requirements and environments. Ongoing development continues to enhance its capabilities.
Use Cases
Nginx finds application across a wide range of domains:
- Static File Serving: Excellent at delivering static assets like CSS, JavaScript, images, audio, and video files, reducing load on dynamic servers.
- Reverse Proxy and Load Balancing: Acts as a reverse proxy to evenly distribute requests among backend servers, increasing system stability and reliability.
- Caching Server: Caches responses to decrease backend load and accelerate data access.
- SSL Acceleration: Enhances HTTPS performance and reduces SSL overhead, ensuring secure communication.
- WebSocket Support: Facilitates real-time communication applications through WebSocket protocol.
- Access Control and Security: Implements IP-based restrictions and access control to improve server security.
In summary, Nginx is a stable and efficient web server and reverse proxy suitable for high-concurrency websites, streaming platforms, IoT, and cloud computing. Its strengths include cross-platform support, simplicity, non-blocking design, high concurrency, event-driven operation, master/worker architecture, low memory footprint, and bandwidth savings. It's extensively used in static serving, reverse proxying, load balancing, caching, SSL acceleration, WebSocket, and access control.
Installation and Deployment
Official Website
Installing via YUM
[root@nginx-71 ~]# 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
module_hotfixes=true
Source Installation
# Navigate to installation directory
cd /usr/local
# Install dependencies
yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel
# Download Nginx package
wget http://nginx.org/download/nginx-1.24.0.tar.gz
# Extract package
tar -xvf nginx-1.24.0.tar.gz
make clean
# Move and enter directory
mv /usr/local/nginx-1.24.0 /usr/local/nginx
cd /usr/local/nginx
# Generate Makefile using configure options (optional)
./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_auth_request_module --with-http_random_index_module
# Compile
make -j2
# Install
make install
# Verify installation (check for nginx process)
ps -ef | grep nginx
# Test configuration file
./nginx -t
# Start service
./nginx -c /usr/local/nginx/conf/nginx.conf
# Reload service (may show nginx.pid errors; refer to online solutions)
./nginx -s reload
# Confirm service started
ps -ef | grep nginx
Configuration Files
Default Nginx Configuration
[root@nginx-71 ~]# cat /etc/nginx/nginx.conf
# User running Nginx processes
user nginx;
# Number of worker processes; 'auto' uses available CPU cores
worker_processes auto;
# Error log path and level
error_log /var/log/nginx/error.log notice;
# PID file location
pid /var/run/nginx.pid;
# Event module settings
events {
worker_connections 1024;
}
# HTTP module settings
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Log format definition
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 settings
access_log /var/log/nginx/access.log main;
# Enable sendfile for efficient file transfers
sendfile on;
# Set keep-alive timeout
keepalive_timeout 65;
# Include additional config files
include /etc/nginx/conf.d/*.conf;
}
Sub Configuration Example
server {
# Listen on port 80
listen 80;
# Define hostnames
server_name example.com www.example.com;
# Document root directory
root /var/www/example.com;
# Default index files
index index.html index.htm;
# Root path handling
location / {
try_files $uri $uri/ /index.html;
}
# Image alias and cache settings
location /images/ {
alias /path/to/images/;
expires 30d;
}
# Reverse proxy configuration
location /api/ {
proxy_pass http://backend_server_address;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# Error page definitions
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
# Error page location
location = /50x.html {
root /var/www/example.com;
}
}
This example defines a virtual host listening on port 80, responding to example.com and www.example.com. Real-world configurations may include more complex directives and options.