正常运行的必备配置:
1、user username [groupname];
指定运行worker进程的用户和组
2、pid /path/to/pidfile_name;
指定nginx的pid文件
3、worker_rlimit_nofile #;
指定一个worker进程所能够打开的最大文件句柄数;
4、worker_rlimit_sigpending #;
设定每个用户能够发往worker进程的信号的数量;
优化性能相关的配置:
1、worker_processes #;
worker进程的个数;通常其数值应该为CPU的物理核心数减1;
2、worker_cpu_affinity cpumask ...;
指定worker只运行在哪颗CPU上,运行在哪颗CPU上,对应位为1。
worker_processes 6;
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000;
3、ssl_engine device;
在存在ssl硬件加速器的服务器上,指定所使用的ssl硬件加速设备;
4、timer_resolution t;
每次内核事件调用返回时,都会使用gettimeofday()来更新nginx缓存时钟;timer_resolution用于定义每隔多久才会由gettimeofday()更新一次缓存时钟;x86-64系统上,gettimeofday()代价已经很小,可以忽略此配置;
5、worker_priority nice;
-20,19之间的值;
事件相关的配置
1、accept_mutex [on|off]
是否打开Ningx的负载均衡锁;此锁能够让多个worker轮流地、序列化地与新的客户端建立连接;而通常当一个worker进程的负载达到其上限的7/8,master就尽可能不再将请求调度此worker;
2、lock_file /path/to/lock_file;
lock文件
3、accept_mutex_delay #ms;
accept锁模式中,一个worker进程为取得accept锁的等待时长;如果某worker进程在某次试图取得锁时失败了,至少要等待#ms才能再一次请求锁;
4、multi_accept on|off;
是否允许一次性地响应多个用户请求;默认为Off;
5、use [epoll|rtsig|select|poll];
定义使用的事件模型,建议让nginx自动选择;
6、worker_connections #;
每个worker能够并发响应最大请求数;
用于调试、定位问题: 只调试nginx时使用
1、daemon on|off;
是否让ningx运行于后台;默认为on,调试时可以设置为off,使得所有信息直接输出到控制台;
2、master_process on|off
是否以master/worker模式运行nginx;默认为on;调试时可设置off以方便追踪;
3、error_log /path/to/error_log level;
错误日志文件及其级别;默认为error级别;调试时可以使用debug级别,但要求在编译时必须使用--with-debug启用debug功能;
nginx的http web功能:
必须使用虚拟机来配置站点;每个虚拟主机使用一个server {}段配置;非虚拟主机的配置或公共配置,需要定义在server之外,http之内;
http {
directive value;
...
server {
}
server {
}
...
}
虚拟主机相关的配置:
1、server {}
定义一个虚拟主机;nginx支持使用基于主机名或IP的虚拟主机;
2、listen
listen address[:port];
listen port
default_server:定义此server为http中默认的server;如果所有的server中没有任何一个listen使用此参数,那么第一个server即为默认server;
rcvbuf=SIZE: 接收缓冲大小;
sndbuf=SIZE: 发送缓冲大小;
ssl: https server;
3、server_name [...];
server_name可以跟多个主机名,名称中可以使用通配符和正则表达式(通常以~开头);当nginx收到一个请求时,会取出其首部的server的值,而后跟众server_name进行比较;比较方式:
(1) 先做精确匹配;www.nginxtest.com
(2) 左侧通配符匹配;*.nginxtest.com
(3) 右侧通配符匹配;www.abc.com, www.*
(4) 正则表达式匹配: ~^.*\.nginxtest\.com$
4、server_name_hash_bucket_size 32|64|128;
为了实现快速主机查找,nginx使用hash表来保存主机名;
5、location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
功能:允许根据用户请求的URI来匹配指定的各location以进行访问配置;匹配到时,将被location块中的配置所处理;比如:http://www.nginxtest.com/images/logo.gif
=:精确匹配;
~:正则表达式模式匹配,匹配时区分字符大小写
~*:正则表达式模式匹配,匹配时忽略字符大小写
^~: URI前半部分匹配,不检查正则表达式
匹配优先级:
字符字面量最精确匹配、正则表达式检索(由第一个匹配到所处理)、按字符字面量
文件路径定义:
1、root path
设置web资源路径;用于指定请求的根文档目录;
location / {
root /www/htdocs;
}
location ^~ /images/ {
root /web;
}
2、alias path
只能用于location中,用于路径别名;
location / {
root /www/htdocs;
}
location ^~ /images/ {
alias /web;
}
3、index file ...;
定义默认页面,可参跟多个值;
4、error_page code ... [=[response]] uri;
当对于某个请求返回错误时,如果匹配上了error_page指令中设定的code,则重定向到新的URI中。
错误页面重定向;
5、try_files path1 [path2 ...] uri;
自左至右尝试读取由path所指定路径,在第一次找到即停止并返回;如果所有path均不存在,则返回最后一个uri;
location ~* ^/documents/(.*)$ {
root /www/htdocs;
try_files $uri /docu/$1 /temp.html;
}
网络连接相关的设置:
1、keepalive_timeout time;
保持连接的超时时长;默认为75秒;
2、keepalive_requests n;
在一次长连接上允许承载的最大请求数;
3、keepalive_disable [msie6 | safari | none ]
对指定的浏览器禁止使用长连接;
4、tcp_nodelay on|off
对keepalive连接是否使用TCP_NODELAY选项;
5、client_header_timeout time;
读取http请求首部的超时时长;
6、client_body_timeout time;
读取http请求包体的超时时长;
7、send_timeout time;
发送响应的超时时长;
对客户端请求的限制:
1、limit_except method ... { ... }
指定对范围之外的其它方法的访问控制;
limit_except GET {
allow 172.16.0.0/16;
deny all;
}
2、client_max_body_size SIZE;
http请求包体的最大值;常用于限定客户所能够请求的最大包体;根据请求首部中的Content-Length来检测,以避免无用的传输;
3、limit_rate speed;
限制客户端每秒钟传输的字节数;默认为0,表示没有限制;
4、limit_rate_after time;
nginx向客户发送响应报文时,如果时长超出了此处指定的时长,则后续的发送过程开始限速;
文件操作的优化:
1、sendfile on|off
是否启用sendfile功能;
2、aio on|off
是否启用aio功能;
3、open_file_cache max=N [inactive=time]|off
是否打开文件缓存功能;
max: 缓存条目的最大值;当满了以后将根据LRU算法进行置换;
inactive: 某缓存条目在指定时长时没有被访问过时,将自动被删除;默认为60s;
缓存的信息包括:
文件句柄、文件大小和上次修改时间;
已经打开的目录结构;
没有找到或没有访问权限的信息;
4、open_file_cache_errors on|off
是否缓存文件找不到或没有权限访问等相关信息;
5、open_file_cache_valid time;
多长时间检查一次缓存中的条目是否超出非活动时长,默认为60s;
6、open_file_cache_min_use #;
在inactive指定的时长内被访问超此处指定的次数地,才不会被删除;
对客户端请求的特殊处理:
1、ignore_invalid_headers on|off
是否忽略不合法的http首部;默认为on; off意味着请求首部中出现不合规的首部将拒绝响应;只能用于server和http;
2、log_not_found on|off
是否将文件找不到的信息也记录进错误日志中;
3、resolver address;
指定nginx使用的dns服务器地址;
4、resover_timeout time;
指定DNS解析超时时长,默认为30s;
5、server_tokens on|off;
是否在错误页面中显示nginx的版本号;
内存及磁盘资源分配:
1、client_body_in_file_only on|clean|off
HTTP的包体是否存储在磁盘文件中;非off表示存储,即使包体大小为0也会创建一个磁盘文件;on表示请求结束后包体文件不会被删除,clean表示会被删除;
2、client_body_in_single_buffer on|off;
HTTP的包体是否存储在内存buffer当中;默认为off;
3、cleint_body_buffer_size size;
nginx接收HTTP包体的内存缓冲区大小;
4、client_body_temp_path dir-path [level1 [level2 [level3]]];
HTTP包体存放的临时目录;
5、client_header_buffer_size size;
正常情况下接收用户请求的http报文header部分时分配的buffer大小;默认为1k;
6、large_client_header_buffers number size;
存储超大Http请求首部的内存buffer大小及个数;
7、connection_pool_size size;
nginx对于每个建立成功的tcp连接都会预先分配一个内存池,此处即用于设定此内存池的初始大小;默认为256;
8、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配置;
1、安装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
1、配置虚拟主机
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;
}
}
2、配置访问控制(只有允许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;
}
}
3、配置用户认证(访问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 "admin
" >> /var/www/html/a/admin/index.html
4、通过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;
}
}
}
5、配置防盗链
(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
www.a.com
cat /var/www/html/b/index.html
www.b.com
6、配置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;
}
}
}
7、配置重写记录到错误日志
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;
}
}
}
8、return code:
用于结束rewrite规则,并且为客户返回状态码;可以使用的状态码有204, 400, 402-406, 500-504等;
9、配置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;
}
}