正常運行的必備配置:html
一、user username [groupname];node
指定運行worker進程的用戶和組nginx
二、pid /path/to/pidfile_name;git
指定nginx的pid文件github
三、worker_rlimit_nofile #;web
指定一個worker進程所可以打開的最大文件句柄數;正則表達式
四、worker_rlimit_sigpending #;算法
設定每一個用戶可以發往worker進程的信號的數量;瀏覽器
優化性能相關的配置:緩存
一、worker_processes #;
worker進程的個數;一般其數值應該爲CPU的物理核心數減1;
二、worker_cpu_affinity cpumask ...;
指定worker只運行在哪顆CPU上,運行在哪顆CPU上,對應位爲1。
worker_processes 6;
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000;
三、ssl_engine device;
在存在ssl硬件加速器的服務器上,指定所使用的ssl硬件加速設備;
四、timer_resolution t;
每次內核事件調用返回時,都會使用gettimeofday()來更新nginx緩存時鐘;timer_resolution用於定義每隔多久纔會由gettimeofday()更新一次緩存時鐘;x86-64系統上,gettimeofday()代價已經很小,能夠忽略此配置;
五、worker_priority nice;
-20,19之間的值;
事件相關的配置
一、accept_mutex [on|off]
是否打開Ningx的負載均衡鎖;此鎖可以讓多個worker輪流地、序列化地與新的客戶端創建鏈接;而一般當一個worker進程的負載達到其上限的7/8,master就儘量再也不將請求調度此worker;
二、lock_file /path/to/lock_file;
lock文件
三、accept_mutex_delay #ms;
accept鎖模式中,一個worker進程爲取得accept鎖的等待時長;若是某worker進程在某次試圖取得鎖時失敗了,至少要等待#ms才能再一次請求鎖;
四、multi_accept on|off;
是否容許一次性地響應多個用戶請求;默認爲Off;
五、use [epoll|rtsig|select|poll];
定義使用的事件模型,建議讓nginx自動選擇;
六、worker_connections #;
每一個worker可以併發響應最大請求數;
用於調試、定位問題: 只調試nginx時使用
一、daemon on|off;
是否讓ningx運行於後臺;默認爲on,調試時能夠設置爲off,使得全部信息直接輸出到控制檯;
二、master_process on|off
是否以master/worker模式運行nginx;默認爲on;調試時可設置off以方便追蹤;
三、error_log /path/to/error_log level;
錯誤日誌文件及其級別;默認爲error級別;調試時可使用debug級別,但要求在編譯時必須使用--with-debug啓用debug功能;
nginx的http web功能:
必須使用虛擬機來配置站點;每一個虛擬主機使用一個server {}段配置;非虛擬主機的配置或公共配置,須要定義在server以外,http以內;
http {
directive value;
...
server {
}
server {
}
...
}
虛擬主機相關的配置:
一、server {}
定義一個虛擬主機;nginx支持使用基於主機名或IP的虛擬主機;
二、listen
listen address[:port];
listen port
default_server:定義此server爲http中默認的server;若是全部的server中沒有任何一個listen使用此參數,那麼第一個server即爲默認server;
rcvbuf=SIZE: 接收緩衝大小;
sndbuf=SIZE: 發送緩衝大小;
ssl: https server;
三、server_name [...];
server_name能夠跟多個主機名,名稱中可使用通配符和正則表達式(一般以~開頭);當nginx收到一個請求時,會取出其首部的server的值,然後跟衆server_name進行比較;比較方式:
(1) 先作精確匹配;www.nginxtest.com
(2) 左側通配符匹配;*.nginxtest.com
(3) 右側通配符匹配;www.abc.com, www.*
(4) 正則表達式匹配: ~^.*\.nginxtest\.com$
四、server_name_hash_bucket_size 32|64|128;
爲了實現快速主機查找,nginx使用hash表來保存主機名;
五、location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
功能:容許根據用戶請求的URI來匹配指定的各location以進行訪問配置;匹配到時,將被location塊中的配置所處理;好比:http://www.nginxtest.com/images/logo.gif
=:精確匹配;
~:正則表達式模式匹配,匹配時區分字符大小寫
~*:正則表達式模式匹配,匹配時忽略字符大小寫
^~: URI前半部分匹配,不檢查正則表達式
匹配優先級:
字符字面量最精確匹配、正則表達式檢索(由第一個匹配到所處理)、按字符字面量
文件路徑定義:
一、root path
設置web資源路徑;用於指定請求的根文檔目錄;
location / {
root /www/htdocs;
}
location ^~ /images/ {
root /web;
}
二、alias path
只能用於location中,用於路徑別名;
location / {
root /www/htdocs;
}
location ^~ /images/ {
alias /web;
}
三、index file ...;
定義默認頁面,可參跟多個值;
四、error_page code ... [=[response]] uri;
當對於某個請求返回錯誤時,若是匹配上了error_page指令中設定的code,則重定向到新的URI中。
錯誤頁面重定向;
五、try_files path1 [path2 ...] uri;
自左至右嘗試讀取由path所指定路徑,在第一次找到即中止並返回;若是全部path均不存在,則返回最後一個uri;
location ~* ^/documents/(.*)$ {
root /www/htdocs;
try_files $uri /docu/$1 /temp.html;
}
網絡鏈接相關的設置:
一、keepalive_timeout time;
保持鏈接的超時時長;默認爲75秒;
二、keepalive_requests n;
在一次長鏈接上容許承載的最大請求數;
三、keepalive_disable [msie6 | safari | none ]
對指定的瀏覽器禁止使用長鏈接;
四、tcp_nodelay on|off
對keepalive鏈接是否使用TCP_NODELAY選項;
五、client_header_timeout time;
讀取http請求首部的超時時長;
六、client_body_timeout time;
讀取http請求包體的超時時長;
七、send_timeout time;
發送響應的超時時長;
對客戶端請求的限制:
一、limit_except method ... { ... }
指定對範圍以外的其它方法的訪問控制;
limit_except GET {
allow 172.16.0.0/16;
deny all;
}
二、client_max_body_size SIZE;
http請求包體的最大值;經常使用於限定客戶所可以請求的最大包體;根據請求首部中的Content-Length來檢測,以免無用的傳輸;
三、limit_rate speed;
限制客戶端每秒鐘傳輸的字節數;默認爲0,表示沒有限制;
四、limit_rate_after time;
nginx向客戶發送響應報文時,若是時長超出了此處指定的時長,則後續的發送過程開始限速;
文件操做的優化:
一、sendfile on|off
是否啓用sendfile功能;
二、aio on|off
是否啓用aio功能;
三、open_file_cache max=N [inactive=time]|off
是否打開文件緩存功能;
max: 緩存條目的最大值;當滿了之後將根據LRU算法進行置換;
inactive: 某緩存條目在指定時長時沒有被訪問過期,將自動被刪除;默認爲60s;
緩存的信息包括:
文件句柄、文件大小和上次修改時間;
已經打開的目錄結構;
沒有找到或沒有訪問權限的信息;
四、open_file_cache_errors on|off
是否緩存文件找不到或沒有權限訪問等相關信息;
五、open_file_cache_valid time;
多長時間檢查一次緩存中的條目是否超出非活動時長,默認爲60s;
六、open_file_cache_min_use #;
在inactive指定的時長內被訪問超此處指定的次數地,纔不會被刪除;
對客戶端請求的特殊處理:
一、ignore_invalid_headers on|off
是否忽略不合法的http首部;默認爲on; off意味着請求首部中出現不合規的首部將拒絕響應;只能用於server和http;
二、log_not_found on|off
是否將文件找不到的信息也記錄進錯誤日誌中;
三、resolver address;
指定nginx使用的dns服務器地址;
四、resover_timeout time;
指定DNS解析超時時長,默認爲30s;
五、server_tokens on|off;
是否在錯誤頁面中顯示nginx的版本號;
內存及磁盤資源分配:
一、client_body_in_file_only on|clean|off
HTTP的包體是否存儲在磁盤文件中;非off表示存儲,即便包體大小爲0也會建立一個磁盤文件;on表示請求結束後包體文件不會被刪除,clean表示會被刪除;
二、client_body_in_single_buffer on|off;
HTTP的包體是否存儲在內存buffer當中;默認爲off;
三、cleint_body_buffer_size size;
nginx接收HTTP包體的內存緩衝區大小;
四、client_body_temp_path dir-path [level1 [level2 [level3]]];
HTTP包體存放的臨時目錄;
五、client_header_buffer_size size;
正常狀況下接收用戶請求的http報文header部分時分配的buffer大小;默認爲1k;
六、large_client_header_buffers number size;
存儲超大Http請求首部的內存buffer大小及個數;
七、connection_pool_size size;
nginx對於每一個創建成功的tcp鏈接都會預先分配一個內存池,此處即用於設定此內存池的初始大小;默認爲256;
八、request_pool_size size;
nginx在處理每一個http請求時會預先分配一個內存池,此處即用於設定此內存池的初始大小;默認爲4k;
http核心模塊的內置變量:
$uri: 當前請求的uri,不帶參數;
$request_uri: 請求的uri,帶完整參數;
$host: http請求報文中host首部;若是請求中沒有host首部,則以處理此請求的虛擬主機的主機名代替;
$hostname: nginx服務運行在的主機的主機名;
$remote_addr: 客戶端IP
$remote_port: 客戶端Port
$remote_user: 使用用戶認證時客戶端用戶輸入的用戶名;
$request_filename: 用戶請求中的URI通過本地root或alias轉換後映射的本地的文件路徑;
$request_method: 請求方法
$server_addr: 服務器地址
$server_name: 服務器名稱
$server_port: 服務器端口
$server_protocol: 服務器向客戶端發送響應時的協議,如http/1.1, http/1.0
$scheme: 在請求中使用scheme, 如https://www.nginxtest.com/中的https;
$http_HEADER: 匹配請求報文中指定的HEADER,$http_host匹配請求報文中的host首部
$sent_http_HEADER: 匹配響應報文中指定的HEADER,例如$http_content_type匹配響應報文中的content-type首部;
$document_root:當前請求映射到的root配置;
一、安裝nginx
groupadd -r nginx
useradd -r -g nginx nginx
yum -y groupinstall "Development Tools"
yum -y install openssl-devel pcre-devel
wget http://nginx.org/download/nginx-1.15.8.tar.gz
tar zxvf nginx-1.15.8.tar.gz
cd nginx-1.15.8
./configure \
--prefix=/usr \
--sbin-path=/usr/sbin/nginx \
--conf-path=/etc/nginx/nginx.conf \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--pid-path=/var/run/nginx/nginx.pid \
--lock-path=/var/lock/nginx.lock \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_flv_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--http-client-body-temp-path=/var/tmp/nginx/client/ \
--http-proxy-temp-path=/var/tmp/nginx/proxy/ \
--http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \
--http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \
--http-scgi-temp-path=/var/tmp/nginx/scgi \
--with-pcre \
--with-http_addition_module
make && make install
爲nginx提供SysV init腳本:
新建文件/etc/rc.d/init.d/nginx,內容以下:
#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig: - 85 15
# description: Nginx is an HTTP(S) server, HTTP(S) reverse \
# proxy and IMAP/POP3 proxy server
# processname: nginx
# config: /etc/nginx/nginx.conf
# config: /etc/sysconfig/nginx
# pidfile: /var/run/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
nginx="/usr/sbin/nginx"
prog=$(basename $nginx)
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
lockfile=/var/lock/subsys/nginx
make_dirs() {
# make required directories
user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
options=`$nginx -V 2>&1 | grep 'configure arguments:'`
for opt in $options; do
if [ `echo $opt | grep '.*-temp-path'` ]; then
value=`echo $opt | cut -d "=" -f 2`
if [ ! -d "$value" ]; then
# echo "creating" $value
mkdir -p $value && chown -R $user $value
fi
fi
done
}
start() {
[ -x $nginx ] || exit 5
[ -f $NGINX_CONF_FILE ] || exit 6
make_dirs
echo -n $"Starting $prog: "
daemon $nginx -c $NGINX_CONF_FILE
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $"Stopping $prog: "
killproc $prog -QUIT
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}
restart() {
configtest || return $?
stop
sleep 1
start
}
reload() {
configtest || return $?
echo -n $"Reloading $prog: "
killproc $nginx -HUP
RETVAL=$?
echo
}
force_reload() {
restart
}
configtest() {
$nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
status $prog
}
rh_status_q() {
rh_status >/dev/null 2>&1
}
case "$1" in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart|configtest)
$1
;;
reload)
rh_status_q || exit 7
$1
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestart|try-restart)
rh_status_q || exit 0
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
exit 2
esac
chmod +x /etc/rc.d/init.d/nginx
chkconfig --add nginx
chkconfig nginx on
service nginx start
一、配置虛擬主機
grep -v ^$ /etc/nginx/nginx.conf | grep -v .*#
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 80;
server_name www.a.com;
root /var/www/html;
}
}
二、配置訪問控制(只有容許192.168.130.53網段訪問)
grep -v ^$ /etc/nginx/nginx.conf | grep -v .*#
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 80;
server_name www.a.com;
root /var/www/html;
allow 192.168.53.0/24;
deny all;
}
}
三、配置用戶認證(訪問www.a.com/admin會彈出認證界面)
grep -v ^$ /etc/nginx/nginx.conf | grep -v .*#
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 80;
server_name www.a.com;
root /var/www/html;
allow 192.168.53.0/24;
deny all;
location /admin/ {
root /var/www/html/;
auth_basic "admin_area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}
}
htpasswd -c -m /etc/nginx/.htpasswd test1
htpasswd -m /etc/nginx/.htpasswd test2
echo "<h1>admin</h1>" >> /var/www/html/a/admin/index.html
四、經過authoindex配置下載站點
編譯的時候須要加 --with-http_addition_module
須要將authoindex.html放到根目錄/var/www/html下
https://raw.githubusercontent.com/phuslu/phuslu.github.io/master/autoindex.html
grep -v ^$ /etc/nginx/nginx.conf | grep -v .*#
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 80;
server_name www.a.com;
root /var/www/html;
allow 192.168.0.0/16;
deny all;
location /admin/ {
root /var/www/html/;
auth_basic "admin_area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location /download/ {
root /var/www/html/;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
charset utf-8;
add_after_body /autoindex.html;
}
}
}
五、配置防盜鏈
(1) 定義合規的引用
valid_referers none | blocked | server_names | string ...;
(2) 拒毫不合規的引用
if ($invalid_referer) {
rewrite ^/.*$ http://www.b.org/403.html
}
防止其餘網站套用www.a.com的圖片文件
grep -v ^$ /etc/nginx/nginx.conf | grep -v .*#
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 80;
server_name www.a.com;
server_name 192.168.60.12;
root /var/www/html;
allow 192.168.0.0/16;
deny all;
location /admin/ {
root /var/www/html/;
auth_basic "admin_area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location /download/ {
root /var/www/html/;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
charset utf-8;
add_after_body /autoindex.html;
}
location ~*\.(jpg|png|gif|jpeg)$ {
root /var/www/html/;
valid_referers none blocked www.a.com *.a.com;
if ($invalid_referer) {
#rewrite ^/ http://www.a.com/403.html;
return 404;
}
}
}
server {
listen 80;
server_name www.b.com;
root /var/www/html/b;
}
}
cat /var/www/html/index.html
<h1>www.a.com</h1>
<img src="http://www.a.com/images/1.png">
cat /var/www/html/b/index.html
<h1>www.b.com</h1>
<img src="http://www.a.com/images/1.png">
六、配置URL rewrite
rewrite regex replacement [flag];
last: 一旦被當前規則匹配並重寫後當即中止檢查後續的其它rewrite的規則,然後經過重寫後的規則從新發起請求;
break: 一旦被當前規則匹配並重寫後當即中止後續的其它rewrite的規則,然後繼續由nginx進行後續操做;
redirect: 返回302臨時重定向;
permanent: 返回301永久重定向;
nginx最多循環10次,超出以後會返回500錯誤;
注意:通常將rewrite寫在location中時都使用break標誌,或者將rewrite寫在if上下文中;
當訪問到download目錄下的jpg、gif、jpeg、png時自動跳轉到images目錄下
grep -v ^$ /etc/nginx/nginx.conf | grep -v .*#
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 80;
server_name www.a.com;
server_name 192.168.60.12;
root /var/www/html;
allow 192.168.0.0/16;
deny all;
location /admin/ {
root /var/www/html/;
auth_basic "admin_area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location /download/ {
root /var/www/html/;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
charset utf-8;
add_after_body /autoindex.html;
rewrite ^/download/(.*\.(jpg|gif|jpeg|png))$ /images/$1 break;
}
}
}
七、配置重寫記錄到錯誤日誌
rewrite_log on|off
是否把重寫過程記錄在錯誤日誌中;默認爲notice級別;默認爲off;
grep -v ^$ /etc/nginx/nginx.conf | grep -v .*#
worker_processes 1;
error_log /var/log/nginx/error.log notice;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 80;
server_name www.a.com;
server_name 192.168.60.12;
root /var/www/html;
allow 192.168.0.0/16;
deny all;
location /admin/ {
root /var/www/html/;
auth_basic "admin_area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location /download/ {
root /var/www/html/;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
charset utf-8;
add_after_body /autoindex.html;
rewrite ^/download/(.*\.(jpg|gif|jpeg|png))$ /images/$1 break;
rewrite_log on;
}
}
}
八、return code:
用於結束rewrite規則,而且爲客戶返回狀態碼;可使用的狀態碼有204, 400, 402-406, 500-504等;
九、配置HTTPS,並將HTTP重定向到HTTPS
用openssl實現私有CA:
生成密鑰對兒:
cd /etc/pki/CA
(umask 077; openssl genrsa -out private/cakey.pem 2048)
生成自簽證書:
openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 3655
建立須要的文件:
touch index.txt serial crlnumber
echo "00" > serial
用openssl實現證書申請:
在主機上生成密鑰,保存至應用此證書的服務的配置文件目錄下, 例如:
mkdir /etc/httpd/ssl
cd /etc/httpd/ssl
(umask 077; openssl genrsa -out httpd.key 1024)
生成證書籤署請求:
openssl req -new -key httpd.key -out httpd.csr
將請求文件發往CA;
CA簽署證書:
簽署:
openssl ca -in /path/to/somefile.csr -out /path/to/somefile.crt -days DAYS
配置HTTPS
grep -v ^$ /etc/nginx/nginx.conf | grep -v .*#
worker_processes 1;
error_log /var/log/nginx/error.log notice;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 443 ssl;
server_name www.a.com;
ssl_certificate /etc/httpd/ssl/httpd.crt;
ssl_certificate_key /etc/httpd/ssl/httpd.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
}
}
將HTTP重定向到HTTPS
grep -v ^$ /etc/nginx/nginx.conf | grep -v .*#
worker_processes 1;
error_log /var/log/nginx/error.log notice;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name www.a.com;
root /var/www/html;
rewrite ^(.*) https://$server_name$1 permanent;
}
server {
listen 443 ssl;
server_name www.a.com;
ssl_certificate /etc/httpd/ssl/httpd.crt;
ssl_certificate_key /etc/httpd/ssl/httpd.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
root /var/www/html;
}
}