ngnix 简介
ngnix 是一款轻量的 web 服务器、反向代理服务器。
特点:内存占用少,启动速度快,高并发能力强。
ngnix 能做什么
- 可以作为网关使用,比如权限拦截、IP 限制。
- 作为代理服务器,下面是我理解的正向和反向代理:
- 正向代理:客户端 --> 代理服务器--> 源服务器
- 反向代理:客户端 --> 代理服务器 <-- 多个源服务器之一
- 可以实现热部署,重新加载配置文件立即生效
- 可以作为 web 服务器来处理静态资源
- 通过路径的正则匹配,更好的处理动态和静态资源。动态资源转发给后端服务,静态资源直接放在 ngnix 上访问。
- 自定义 HTTP header,比如跨域所用到的一些 header 属性。
- 实现负载均衡,一个请求可以访问多台服务器来减小服务器压力。
- 数据缓存
其实可以做的事情很多,很强大了。那么对于前端而言以下几点比较常用:
- 代理一些域名
- 静态资源服务器:项目部署,前后端可以发到同一域名下。
- 通过在 ngnix.conf 中正则定义一些路径及其资源,比如 /api 路径转发给后端, /app 路径访问前端静态资源,/error 路径访问项目异常页面。也可以定义一些简单接口数据返回
- 定义一些 HTTP Header,比如一些跨域请求的 Header。
ngnix 配置文件
具体配置文件的文档可以参考:https://www.nginx.com/resources/wiki/start/topics/examples/full/
worker_processes 5; ## Default: 1
error_log logs/error.log;
pid logs/nginx.pid;
worker_rlimit_nofile 8192;
events {
worker_connections 4096; ## Default: 1024
}
http {
include conf/mime.types;
include /etc/nginx/proxy.conf;
include /etc/nginx/fastcgi.conf;
index index.html index.htm index.php;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] $status '
'"$request" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log logs/access.log main;
sendfile on;
tcp_nopush on;
server_names_hash_bucket_size 128; # this seems to be required for some vhosts
server { # php/fastcgi
listen 80;
server_name domain1.com www.domain1.com;
access_log logs/domain1.access.log main;
root html;
location ~ \.php$ {
fastcgi_pass 127.0.0.1:1025;
}
}
server { # simple reverse-proxy
listen 80;
server_name domain2.com www.domain2.com;
access_log logs/domain2.access.log main;
# 服务器静态文件
location ~ ^/(images|javascript|js|css|flash|media|static)/ {
root /var/www/virtual/big.server.com/htdocs;
expires 30d;
}
# pass requests for dynamic content to rails/turbogears/zope, et al
location / {
proxy_pass http://127.0.0.1:8080;
}
}
## 负载均衡
upstream big_server_com {
server 127.0.0.3:8000 weight=5;
server 127.0.0.3:8001 weight=5;
server 192.168.0.1:8000;
server 192.168.0.1:8001;
}
server { # simple load balancing
listen 80;
server_name big.server.com;
access_log logs/big.server.access.log main;
location / {
proxy_pass http://big_server_com;
}
}
}
TODO
学习再好还不如动手实践,之后自己去搞个 ngnix 服务跑一跑。