Nginx(engine X) 是一個高性能的 HTTP 服務器和反向代理服務器,這款軟件開發的目的是為了解決 C10k 問題。
Nginx 的架構利用了許多現代操作系統的特性,以實現一個高性能的 HTTP 服務器。例如在 Linux 系統上,Nginx 使用了 epoll,sendfile,File AIO,DIRECTIO 等機制,使得 Nginx 不僅性能高效,而且資源占用率非常低,官方宣稱 nginx 維持 10000 個非活動的 HTTP keep-alive 連接僅需要 2.5M 內存。
Nginx會按需同時運行多個進程:一個主進程(master)和幾個工作進程(worker),配置了緩存時還會有緩存加載器進程(cache loader)和緩存管理器進程(cache manager)等。所有進程均是僅含有一個線程,并主要通過“共享內存”的機制實現進程間通信。主進程以 root 用戶身份運行,而worker、cache loader 和 cache manager 均應以非特權用戶身份運行。
1. 安裝 nginx
在 CentOS6 版本的 EPEL 源中,已經加入了 nginx 的 rpm 包,不過此 RPM 包版本較低。如果需要更新版本,可以使用官方制作的 rpm 包,或者使用源碼包編譯安裝。
還可以使用一些二次開發功能增強的 nginx 版本,例如淘寶的 Tengine 和 OpenResty 都是不錯的選擇。
1.1 常用編譯參數
--prefix=PATH:指定 nginx 的安裝目錄
--conf-path=PATH:指定 nginx.conf 配置文件路徑
--user=NAME:nginx 工作進程的用戶
--with-pcre:開啟 PCRE 正則表達式的支持
--with-http_ssl_module:啟動 SSL 的支持
--with-http_stub_status_module:用于監控 Nginx 的狀態
--with-http-realip_module:允許改變客戶端請求頭中客戶端 IP 地址
--with-file-aio:啟用 File AIO
--add-module=PATH:添加第三方外部模塊
這里提供一個完整的編譯方案:
--prefix=/usr/local/nginx /
--conf-path=/etc/nginx/nginx.conf /
--error-log-path=/var/log/nginx/error.log /
--http-log-path=/var/log/nginx/access.log /
--http-client-body-temp-path=/var/tmp/nginx/client_body /
--http-proxy-temp-path=/var/tmp/nginx/proxy /
--http-fastcgi-temp-path=/var/tmp/nginx/fastcgi /
--http-uwsgi-temp-path=/var/tmp/nginx/uwsgi /
--pid-path=/var/run/nginx.pid /
--lock-path=/var/lock/nginx /
--user=nginx /
--group=nginx /
--with-file-aio /
--with-http_ssl_module /
--with-http_realip_module /
--with-http_sub_module /
--with-http_gzip_static_module /
--with-http_stub_status_module /
--with-pcre
1.2 nginx 的啟動和關閉
啟動 nginx:
# nginx -c /etc/nginx/nginx.conf
關閉 nginx
# nginx -s stop
重讀配置文件
# nginx -s reload# pkill -HUP nginx
重新打開日志文件
# nginx -s reopen# pkill -USR1 nginx
還可以下載 nginx RPM 包中的 /etc/init.d/nginx 文件,修改路徑后即可使用:
# service nginx {start|stop|status|restart|reload|configtest|}
2. nginx.conf 配置文件
Nginx 配置文件主要分成四部分:main(全局設置)、http(HTTP 的通用設置)、server(虛擬主機設置)、location(匹配 URL 路徑)。還有一些其他的配置段,如 event,upstream 等。
新聞熱點
疑難解答