Appearance
Nginx 基础配置
Nginx的配置文件结构清晰,功能强大。本章将详细介绍Nginx的基础配置。
配置文件结构
Nginx的配置文件采用层次结构,主要包含以下几个部分:
- main(全局设置): 全局配置参数
- events(事件设置): 连接处理相关配置
- http(主服务器设置): HTTP服务器相关配置
全局配置块
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
Events块
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 block)用于定义虚拟主机配置:
server {
listen 80;
server_name example.com;
root /var/www/example.com;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
Location块详解
Location块用于定义URL路径的处理规则:
location /images/ {
root /var/www/images;
}
location ~* \.(jpg|jpeg|png|gif)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
常用配置指令
重定向配置
server {
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
静态文件服务
location /static/ {
alias /var/www/static/;
expires 30d;
add_header Cache-Control "public";
}
Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;