一般情况下部署网站的服务器,Asp.net使用IIS,Jsp/Servlet使用tomcat,PHP使用Apache,但nginx相比较它们有着轻量级、高性能、并发能力强的突出优点,尤其是在静态资源的处理上速度快而占用内存少。
使用nginx最主要的一个考虑是使用它的反向代理功能。使用nginx对网站的静态页面和动态页面分别处理,对大量密集的访问有针对性实施负载平衡策略。
下载:nginx news
安装比较简单,解压缩到某一个目录即可,妥妥的绿色软件,常用命令:
start nginx 启动nginx(默认的端口号是80)
nginx -s stop 快速关闭nginx,可能不保存相关信息并迅速关闭web服务
nginx -s -quit 正常关闭nginx,保存相关信息后关闭web服务
nginx -s reload 重新加载nginx配置(nginx支持热部署)
nginx -v 显示nginx版本
nginx -V 显示nginx版本、编译器版本、配置参数
nginx -t 检查配置文件是否正常
更改配置参数后,使用nginx -s reload即可完成参数的重新加载。
配置文件:在conf目录下,名为nginx.conf,具体参数含义:
#user nobody;
worker_processes 1; #nginx运行的进程数,可以根据服务器的硬件配置进行更改
#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; #nginx的最大连接数,1024是默认值
}
http {
include mime.types; #在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; #开启高效传输模式,允许sendfile方式传输文件
#tcp_nopush on; #防止网络阻塞
#keepalive_timeout 0;
keepalive_timeout 65; #长连接的超时时间(单位秒)
#gzip on; #开启gzip压缩,加快传输速度
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;
# }
#}
}
正向代理和反向代理的区别:
正向代理的请求转发在客户端,反向代理的请求转发在代理端。
简单理解:如果你直接访问了目的地址,那应用的就是正向代理,如果你是访问的中间服务器(通过中间服务器访问目的地址),那应用的就是反向代理。
正向代理时:
nginx的最大连接数=worker_processes * worker_connections
最为反向代理时:
nginx的最大连接数=worker_processes * worker_connections/4