引言
Nginx作为目前最流行的Web服务器之一,凭借其高性能、低资源消耗和丰富的功能模块,成为众多企业和开发者的首选。然而,默认安装的Nginx并不能发挥最佳性能,合理的配置与优化是提升网站访问速度、保障服务稳定性的关键。本文将带您从基础安装到深度优化,全面掌握Nginx配置实战技巧。
一、Nginx安装与基础配置
首先更新系统并安装Nginx:
sudo apt update
sudo apt install nginx -y安装完成后,启动Nginx并设置开机自启:
systemctl start nginx
systemctl enable nginx基础配置文件通常位于/etc/nginx/nginx.conf和/etc/nginx/sites-enabled/目录下。我们先了解主配置文件结构:
user www-data;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
server {
listen 80;
server_name localhost;
root /var/www/html;
index index.html index.htm;
}
}二、核心性能参数优化
worker_processes参数设置为auto可以让Nginx自动检测CPU核心数,充分利用多核处理器性能。worker_connections设置每个工作进程的最大连接数,需要根据服务器内存和访问量调整:
worker_processes auto;
worker_rlimit_nofile 100000;
events {
worker_connections 4096;
multi_accept on;
use epoll;
}在http段添加以下优化参数:
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
client_max_body_size 100m;
# 开启Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}三、负载均衡配置实战
对于高流量网站,单台服务器往往无法满足需求,Nginx的负载均衡功能可以将请求分发到多个后端服务器:
http {
upstream backend {
least_conn;
server 192.168.1.101:8080 weight=3;
server 192.168.1.102:8080 weight=2;
server 192.168.1.103:8080 backup;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}以上配置使用least_conn算法,根据后端服务器连接数分配请求,weight参数设置服务器权重,backup标记备用服务器。
四、安全加固配置
保障服务器安全是每个运维人员的重要职责,以下是Nginx安全优化配置:
server {
listen 80;
server_name example.com;
# 隐藏Nginx版本号
server_tokens off;
# 限制请求频率
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
limit_req zone=one burst=5 nodelay;
# 防止目录遍历
location ~ /\. {
deny all;
}
# 禁止执行脚本
location ~* \.(php|pl|py|jsp|asp|sh|cgi)$ {
deny all;
}
# 设置安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
}五、日志优化与监控
合理的日志配置有助于问题排查和性能分析:
http {
log_format custom '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"';
access_log /var/log/nginx/access.log custom;
error_log /var/log/nginx/error.log warn;
# 日志缓冲设置
access_log /var/log/nginx/access.log custom buffer=32k flush=1m;
}可以使用awk命令分析访问日志,找出访问最多的IP:
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -20六、完整配置文件示例
以下是一个综合优化的Nginx配置文件:
user www-data;
worker_processes auto;
worker_rlimit_nofile 100000;
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;
events {
worker_connections 4096;
multi_accept on;
use epoll;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 性能优化参数
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
client_max_body_size 100m;
# Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# 日志格式
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time';
access_log /var/log/nginx/access.log main buffer=32k flush=1m;
# 负载均衡配置
upstream php_backend {
least_conn;
server 127.0.0.1:9000 weight=5;
server 192.168.1.100:9000 weight=3;
}
# 主站点配置
server {
listen 80;
server_name example.com www.example.com;
server_tokens off;
root /var/www/html;
index index.php index.html index.htm;
# 安全设置
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
# 请求限制
limit_req_zone $binary_remote_addr zone=login:10m rate=10r/m;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# PHP处理
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass php_backend;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
# 静态文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
add_header Cache-Control "public, immutable";
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
}
}总结
Nginx的配置优化是一个持续的过程,需要根据实际业务需求和服务器性能不断调整。本文介绍了从安装到性能优化、负载均衡、安全加固和日志管理的完整配置方案。建议读者在实际部署前,先在测试环境验证配置,使用nginx -t命令检查配置文件语法,然后逐步应用到生产环境。记住,没有一劳永逸的最佳配置,只有最适合当前业务需求的配置方案。定期监控服务器性能指标,根据访问日志分析调整参数,才能让Nginx服务器始终保持最佳运行状态。