Nginx 配置
大约 2 分钟
Nginx 基础配置
配置文件 nginx.config
:
user nginx;
# 工作进程的数量
worker_processes auto;
# 错误日志记录
error_log /var/log/nginx/error.log notice;
# nginx pid 存储位置
pid /var/run/nginx.pid;
events {
# 单个进程可接受连接数
worker_connections 1024;
}
http {
# mime.types 文件里面包含的是 http 请求头 content_type 内容
include /etc/nginx/mime.types;
# 如果mime类型没匹配上,默认使用二进制流的方式传输
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;
# 使用 linux 的 sendfile(socket, file, len) 高效网络传输,也就是数据0拷贝
sendfile on;
#tcp_nopush on;
# 长连接保持时间
keepalive_timeout 65;
#gzip on;
# 引入其它的配置文件
include /etc/nginx/conf.d/*.conf;
}
/etc/nginx/conf.d/
文件下的 default.conf
# 虚拟主机配置
server {
# 监听端口
listen 80;
# 服务主机名
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
# 资源匹配路径
location / {
# 文件根目录
root /usr/share/nginx/html;
# 默认页面名称
index index.html index.htm;
}
# 404 状态码页面
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
# 异常页面 错误码 对应的静态资源
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
root 指令
用于设置请求的文档根目录,它指定了一个路径,Nginx 会将客户端请求的 URI 拼接到该路径,从而定位到服务器上的文件。
例如:
location / {
root /var/www/html;
index index.html;
}
请求 http://example.com/
时,Nginx 会查找 /var/www/html/index.html
。
提示
root 指令可以直接配置在 server
指令中,也可以配置在 location
指令内,配置在 server
中时,其它 location
指令配置如果没有显示声明 root
那么将默认继承最外层的 root
指令配置。
alias 指令
用于将某个 URI 路径直接映射到文件系统中的指定路径,不拼接 URI 的其他部分。它通常用于处理需要将请求路径映射到与文件系统路径不直接对应的情况。
例如:
location /static/ {
alias /var/www/media/;
index index.html;
}
请求 http://example.com/static/
时,Nginx 会查找 /var/www/media/index.html
。
try_files 指令
用来按照顺序检查多个文件或资源是否存在,并根据找到的第一个可用资源来处理请求。如果找不到任何资源,还可以定义一个默认的处理方式(例如返回错误页面或代理请求到其他服务)。
error_page 指令
用来指定错误码(如 404)时显示的自定义页面,并保留对应的 HTTP 状态码。
server {
# 404 状态码页面
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
# 异常页面 错误码 对应的静态资源
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}