使用场景
- 高并发,高性能
- 可扩展性好
- 高可靠性
- 支持热部署
- BSD 许可证,可二次开发并用于商用
运行文件组成
共由 4 部分组成,分别是:
Nginx 二进制可执行文件
服务的主体,由各个模块的源码编译出来的
Nginx.conf 配置文件
用来控制 Nginx 的行为
access.log 访问日志
记录一条 http 请求信息(请求、响应)
error.log 错误日志
用来定位问题
配置文件通用语法
#user nobody;worker_processes 1;#error_log logs/error.log;#error_log logs/error.log notice;#error_log logs/error.log info;#pid logs/nginx.pid;events {worker_connections 1024;}http {include 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 logs/access.log main;sendfile on;#tcp_nopush on;#keepalive_timeout 0;keepalive_timeout 65;#gzip on;server {listen 80;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;location / {root html;index index.html index.htm;}#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 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;#}}# another virtual host using mix of IP-, name-, and port-based configuration##server {# listen 8000;# listen somename:8080;# server_name somename alias another.alias;# location / {# root html;# index index.html index.htm;# }#}# HTTPS server##server {# listen 443 ssl;# server_name localhost;# ssl_certificate cert.pem;# ssl_certificate_key cert.key;# ssl_session_cache shared:SSL:1m;# ssl_session_timeout 5m;# ssl_ciphers HIGH:!aNULL:!MD5;# ssl_prefer_server_ciphers on;# location / {# root html;# index index.html index.htm;# }#}}
- 配置文件由指令和指令块组成
- 每条指令以分号
;结尾 - 指令与参数之间以空格隔开,几个空格无所谓
- 指令块以大括号
{}将多条指令组合在一起 - include 允许组合多个配置文件,提高可维护性、可阅读性
- 注释使用
#在每行开头 - 以
$开头的是变量 - 部分指令的参数支持正则表达式
- 空间、容量配置时,不写单位默认是
bytes
http 指令块由 server、upstream、location 三个指令块组成。
运行时的进程结构
[root@localhost nginx]# ps -ef | grep nginxroot 20126 1 0 00:11 ? 00:00:00 nginx: master process ./sbin/nginx -c /home/xu-dev/nginx/conf/nginx.confroot 20132 20126 0 00:12 ? 00:00:00 nginx: worker processroot 20133 20126 0 00:12 ? 00:00:00 nginx: worker processroot 20134 20126 0 00:12 ? 00:00:00 nginx: worker process
Nginx 由两种进程组成,分别被称为 Master 进程和 Worker 进程;真正接收处理请求的是 Worker 进程,而 Master 进程负责管理 Worker 进程是否正常工作、是否需要重新载入配置文件、是否需要热部署……
多进程的方式保证了 Nginx 的高可靠性,那么为了在实际使用的时候能够最大化对硬件的使用率,我们通常会把 Worker 进程的数量配置成与 CPU 核心数一致,并且分别将每个进程绑定到每颗 CPU 上。
虚拟主机
利用虚拟主机,可以一台或一组 Nginx 服务器可以运行多个网站。
在 nginx.conf中,每个 server命令块代表一个虚拟主机。
http {server {listen 80;location / {index index.html;}}}
