nginx 入门配置
nginx是一个高性能的HTTP和反向代理服务器。
常使用场景:
1、反向代理
2、网站负载均衡
nginx 配置文件入口: /etc/nginx/下的nginx.conf文件
user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/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 /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; gzip on; include /etc/nginx/conf.d/*.conf; }
worker_processes:指明了nginx要开启的进程数,据官方说法,一般开一个就够了,多开几个,可以减少机器io带来的影响。 一般为当前机器总cpu核心数的1到2倍,可与worker_cpu_affinity连用指定CPU。
error_log:异常日志输出目录
worker_connections:指定并发连接数,一般与worker_rlimit_nofile连用
worker_rlimit_nofile:指定同时处理的文件限制
http: 详细网站配置
http[include] :指包含文件,可以把配置文件存储在其他位置,如把网站每个server以单独文件形式存放在/etc/nginx/conf.d/下。
http[gzip]:gzip压缩相关配置,是否开启压缩,压缩内容,压缩的等级等等
http[server]:网站服务的各项配置,包含监听,主机头,文件路径,网站目录,是否代理,重定向等等配置
http[upstream]:负载均衡各项配置,服务器地址,权重,启停、备用等等配置
普通网站配置示例:
server { listen 80; server_name localhost; location / { 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 # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }
https网站示例:
server { listen 443 ssl; server_name ***.com; ssl_certificate /etc/nginx/server.crt; ssl_certificate_key /etc/nginx/server.key; location / { 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 # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }
listen: 监听端口,加ssl 为https通信方式。
server_name:网站服务名,主机头
error_page:错误页
location: 虚拟位置,如 “/” 根目录,如“/images/”,“/50x.htm"等等
root:文件实际位置
index:起始页
ssl_certificate:ssl证书存放位置(由证书颁发机构提供)
ssl_certificate_key:ssl证书私钥存放位置(由证书颁发机构提供)
网站代理设置示例:
server {
listen 80;
server_name ***.com;
location / {
proxy_pass http://192.168.1.101;
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 300;
proxy_set_header HOST $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
#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 /usr/share/nginx/html;
}
}
网站负载均衡示例:
upstream BlanceServers{
server 192.168.1.101:80 weight=10;
server 192.168.1.102:80 weight=5;
}
server {
listen 80;
server_name ***.com;
location / {
proxy_pass http://BlanceServers;
proxy_connect_timeout 300;
...
proxy_pass:代理路径配置可以是具体网站地址,也可以是负载均衡名称
upstream:负载均衡配置节点,注意它是在http节点下的
详见官网文档:http://nginx.org/en/docs/