安装:
yum install -i nginx
运行:
nginx
查看是否运行成功:
netstat -pln|grep nginx
若没有运行成功,应该是80端口被占用,输入 netstat -pln|grep 80 找到80端口的进程id 。 输入 kill -9 进程id 结束进程并重启nginx 。
配置:
配置文件路径 /etc/nginx 输入下面命令可以对nginx 端口、根目录、错误页面等进行配置
vim /etc/nginx/nginx.conf
全局配置
# 并发数配置,默认auto,值越大并发处理量越多,受硬件影响
worker_processes auto;
events配置
# 最大连接数
worker_connections 1024;
http配置
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; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream;
server配置
#监听端口 listen 80 default_server; listen [::]:80 default_server; #服务器名称 server_name _; # 根目录 root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { }
location 配置
nginx常用命令
版本号
nginx -v
启动
nginx
停止
nginx -s stop
重加载
nginx -s reload
nginx反向代理 (访问nginx, 间接访问代理地址)
在location中添加 proxy_pass 代理地址
location / {
proxy_pass http://localhost:8080;
}
nginx负载均衡
# 首先在根配置中配置多个服务器
upstream myserver {
server localhost:8081;
server localhost:8080;
}# 然后在location / 配置反向代理
location / {
proxy_pass http://myserver;
}
负载均衡分配策略
1. 轮询(默认)
服务器按照请求时间顺序,逐一分配到各个服务器上,如果服务器down掉,自动剔除
2. weight (权重)
默认权重为1,权重越高,被分配的请求越多。
upstream myserver {
server localhost:8081 weight=10;
server localhost:8080 weight=5;
}
3. ip_hash
使每个ip每次请求访问同一个服务器(解决session共享问题)
upstream myserver {
ip_hash;
server localhost:8081;
server localhost:8080;
}
4. fair
按照服务器响应时间分配,响应时间短的优先分配。
upstream myserver {
server localhost:8081;
server localhost:8080;
fair;
}
nginx动静分离
部署静态文件
location /music {
# 静态文件路径
root /usr/share/nginx/;# 设置index文件
index index.html index.htm;# 是否可以浏览文件夹
autoindex on;
}