nginx.conf为服务器的配置文件,配置文件采用文件块的方式,每个块都有其作用域,分别有全局配置、events、http块、server块、location块等,以{}结束。
配置介绍
# 以下为全局生效配置
user nginx; # 使用nginx用户启动进程,user user [group]
worker_processes auto; # 配置允许生成的进程数,自动
error_log /var/log/nginx/error.log notice; # 配置错误日志存放路径和级别
pid /var/run/nginx.pid; # 程序进程ID存放路径
# events块,设置进程最大连接数
events {
worker_connections 1024;
}
# 以下是http块,包含了http全局应用和server块
http {
# http全局块
# 引入配置文件,使用include调用其它配置文件,定义MIME type浏览器支持显示的资源类型
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 设置服务器日志的格式,配合access_log使用
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# 设置服务日志,nginx服务器对前端响应日志
access_log /var/log/nginx/access.log main;
# 配置sendfile传输模式
sendfile on;
#tcp_nopush on;
# 配置连接超时时间
keepalive_timeout 65;
# 开启服务器压缩
#gzip on;
# 导入文件
include /etc/nginx/conf.d/*.conf;
# server块,包含server全局块和location块
server {
# 配置网络监听,listen ip:port ,或者listen 80监控所有地址的80端口
listen 80;
# 虚拟主机的定义,通过server_name指定外部服务此server块提供的服务,server_name 可用写多个,以第一个为主,可用使用*和正则表达式进行匹配
# 基于ip的虚拟主机,如果服务器是多网卡的server_name可以指定ip地址,server_name 192.168.1.1
server_name localhost;
# access_log 可以在server块使用,效果是每个虚拟主机的日志分别存储
#access_log /var/log/nginx/host.access.log main;
# location匹配请求操作,格式location [ = | ~ | ~* | ^~ ] uri {},可以使用正则表达式进行条件匹配,符合条件的进行location下的操作
# “/”通用匹配,任何请求都能匹配到。建议是先进行精确匹配,最后通用匹配,类似与ACL规则一样。
# 所有请求都匹配到,任何执行root和index
location / {
# 指定请求执行目录/usr/share/nginx/html
root /usr/share/nginx/html;
# 设置网站的默认首页,可以设置多个变量,空格隔开
index index.html index.htm;
}
# 错误页,设置自定义错误页
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
# 设置50X错误页面,通过一个location进行设置路径
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# PHP配置代理
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# 配置PHP代理到9000本地端口
# 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;
#}
}
}
# 上面是一个简单的配置文件
# 还有一个基本的访问控制,允许或者拒绝ip地址,可以是主机地址或者网段,可以在http、server、location块中使用
allow address | CIDR | ALL;
deny address | CIDR | ALL;
# nginx密码认证,基于ngx_http_auth_basic_module标准模块
auth_basic string | off # 配置认证时的提示信息string并开启认证 或者off关闭此功能
auth_basic_user_file file #配置用户和密码信息,支持明文和加密
配置思路:
全局块和http块全局配置,然后每个server可以独立设置,一个虚拟主机运行一个程序,server块下面的location执行指定的匹配条件。
框架:
# nginx.conf
# 全局配置
# http块
http{
# server1
server{
location{
...
}
location{
...
}
}
# server2
server{
location{
...
}
location{
...
}
}
# server3
server{
location{
...
}
location{
...
}
}
}