Nginx的配置文件采用层次化的结构设计,主要由指令(directives)和上下文(contexts)组成。下面我将详细介绍Nginx配置文件的结构方法。
Nginx配置文件通常位于以下位置:
- 主配置文件:/etc/nginx/nginx.conf
- 其他配置文件:/etc/nginx/conf.d/
或 /etc/nginx/sites-enabled/
全局块(Global Context)
nginx
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events块
nginx
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
http块
示例:
http {
include /etc/nginx/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 /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
server块
示例:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
location块
示例:
location /images/ {
alias /data/images/;
expires 30d;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
模块化配置
include
指令将配置分割到多个文件中nginx
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
虚拟主机配置
/etc/nginx/sites-available/
目录下/etc/nginx/sites-enabled/
启用常用配置分离
nginx
include /etc/nginx/ssl.conf;
include /etc/nginx/gzip.conf;
检查配置文件语法:
nginx -t
重载配置(不中断服务):
nginx -s reload
对于更复杂的应用,Nginx配置可以包含:
upstream块:定义负载均衡后端服务器组
upstream backend {
server backend1.example.com;
server backend2.example.com;
keepalive 32;
}
map块:创建变量映射
map $http_user_agent $is_mobile {
default 0;
"~*android|iphone" 1;
}
geo块:基于IP地址创建变量
geo $geo {
default unknown;
192.168.1.0/24 internal;
}
通过合理组织Nginx配置文件结构,可以提高配置的可读性、可维护性和重用性,使服务器管理更加高效。