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/