http://nginx.org/
http://www.nginx.cn/doc/
https://github.com/nginx/nginx
nginx基本介绍
- web服务器
- 代理服务器
- C语言编写
- 开源
为什么选择nginx
- 高性能 高并发
- 高扩展性(功能模块化)
- 高可靠性(持续不断运行)
nginx应用场景
- nginx web服务
- nginx代理
- nginx反向代理----->负载均衡
- nginx反向代理----->缓存
- nginx静态加速
- nginx动静分离
- nginx 全站https
nginx安装
nginx官方源
vim /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
安装
yum install nginx
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;
use epoll;
}
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;
}
nginx运行一个网站
vim /etc/nginx/conf.d/game.wuxing.com.conf
server {
listen 80;
server_name game.wuxing.com;
location / {
root /code;
index index.html;
}
}
nginx虚拟主机
- 基于IP(几乎不用)
- 基于端口(内部使用)
- 基于域名
cat /etc/nginx/conf.d/game.wuxing.com.conf
server {
listen 80;
server_name game.wuxing.com;
location / {
root /code;
index index.html;
}
}
cat /etc/nginx/conf.d/gd.wuxing.com.conf
server {
listen 80;
server_name gd.wuxing.com;
location / {
root /code2;
index index.html;
}
}
autoindex
vim /etc/nginx/conf.d/mirrors.wuxing.com.conf
server {
listen 80;
server_name mirror.wuxing.com;
location / {
root /code;
index index.html;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
}
}
core_module
http://nginx.org/en/docs/http/ngx_http_core_module.html
worker_processes
Syntax: worker_processes number | auto;
Default: worker_processes 1;
Context: main
定义worker进程数
load_module
Syntax: load_module file;
Default: —
Context: main
This directive appeared in version 1.9.11.
加载动态模块
user
Syntax: user user [group];
Default: user nobody nobody;
Context: main
pid
Syntax: pid file;
Default: pid logs/nginx.pid;
Context: main
events
Syntax: events { ... }
Default: —
Context: main
worker_connections
Syntax: worker_connections number;
Default: worker_connections 512;
Context: events
设置worker进程的最大同时连接数
use
Syntax: use method;
Default: —
Context: events
method
- select
- poll
- epoll
include
Syntax: include file | mask;
Default: —
Context: any
types
Syntax: types { ... }
Default:
types {
text/html html;
image/gif gif;
image/jpeg jpg;
}
Context: http, server, location
default_type
http://nginx.org/en/docs/http/ngx_http_core_module.html#default_type
Syntax: default_type mime-type;
Default: default_type text/plain;
Context: http, server, location
基于IP实现访问控制
ngx_http_access_module
匹配到一条规则不再执行后面的规则
location / {
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all;
}
基于用户名和密码的访问控制
ngx_http_auth_basic_module
[root@web01 ~]# yum install httpd-tools
[root@web01 ~]# htpasswd -bc /etc/nginx/pass_file wuxing 123456
Adding password for user oldboy
[root@web01 ~]# cat /etc/nginx/pass_file
oldboy:FuD2.sNj9En4c
chmod 400 /etc/nginx/pass_file
chown www /etc/nginx/pass_file
[root@web01 conf.d]# cat basic.conf
server {
listen 80;
server_name basic.oldboy.com;
root /code;
index index.html;
location / {
auth_basic "Please input passwd!";
auth_basic_user_file /etc/nginx/pass_file;
}
}
连接限制(limit_conn)
ngx_http_limit_conn_module
Syntax: limit_conn_zone key zone=name:size;
Default: —
Context: http
Syntax: limit_conn zone number;
Default: —
Context: http, server, location
Syntax: limit_conn_status code;
Default: limit_conn_status 503;
Context: http, server, location
This directive appeared in version 1.3.15.
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location /download/ {
limit_conn addr 1;
}
请求限制 (limit_req)
ngx_http_limit_req_module
Syntax: limit_req_zone key zone=name:size rate=rate [sync];
Default: —
Context: http
Syntax: limit_req zone=name [burst=number] [nodelay | delay=number];
Default: —
Context: http, server, location
limit_req_zone $binary_remote_addr zone=perip:10m rate=1r/s;
limit_req_zone $server_name zone=perserver:10m rate=10r/s;
server {
...
limit_req zone=perip burst=5 nodelay;
limit_req zone=perserver burst=10;
}
Syntax: limit_req_status code;
Default:
limit_req_status 503;
Context: http, server, location
This directive appeared in version 1.3.15.
Syntax: limit_req_log_level info | notice | warn | error;
Default:
limit_req_log_level error;
Context: http, server, location
This directive appeared in version 0.8.18.
限速
ngx_http_core_module
Syntax: limit_rate rate;
Default:
limit_rate 0;
Context: http, server, location, if in location
Syntax: limit_rate_after size;
Default:
limit_rate_after 0;
Context: http, server, location, if in location
This directive appeared in version 0.8.0.
location /flv/ {
flv;
limit_rate_after 500k;
limit_rate 50k;
}
错误页面
error_page 503 ... @error_503;
location @error_503 {
default_type text/html;
return 200 "xxxxxxx";
}
nginx状态
ngx_http_stub_status_module
Syntax: stub_status;
Default: —
Context: server, location
location = /basic_status {
stub_status;
}
Active connections: 291
server accepts handled requests
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106
-
Active connections
The current number of active client connections including Waiting connections.
当前活动的客户端连接数,包括Waiting连接数 -
accepts
The total number of accepted client connections.
接受的客户端连接总数 -
handled
The total number of handled connections. Generally, the parameter value is the same as accepts unless some resource limits have been reached (for example, the worker_connections limit).
已处理的连接总数 -
requests
The total number of client requests.
客户端请求总数 -
Reading
The current number of connections where nginx is reading the request header.
nginx正在读取请求标头的当前连接数 -
Writing
The current number of connections where nginx is writing the response back to the client.
nginx正在将响应写回到客户端的当前连接数 -
Waiting
The current number of idle client connections waiting for a request.
当前等待请求的空闲客户端连接数
location
http://nginx.org/en/docs/http/ngx_http_core_module.html#location
匹配请求URI
Syntax: location [ = | ~ | ~* | ^~ ] uri { … }
location @name { … }
Default: —
Context: server, location
location | [ = | ~ | ~* | ^~ | @ ] | uri | {…} |
---|---|---|---|
指令 | 匹配标识 | 匹配的网站网址 | 匹配URI后要执行的配置段 |
特殊字符
符号 | 含义 |
---|---|
~ | 区分大小写 |
~* | 不区分大小写 |
! | 取反 |
^~ | 在常规的字符串匹配检查之后,不做正则表达式的检查 |
location字符组合匹配顺序
1、 location = / {" | 精确匹配 |
---|---|
2、 location ^~ /images/ {" | 匹配常规字符串,不做正则匹配检查 |
3、 location ~* .(gif|jpg|jpeg)$ {" | 正则匹配 |
4、 location /document/ {" | 匹配常规字符串,如果有正则则优先匹配正则 |
5、 location / {" | 所有location都不能匹配后的默认匹配 |
location = / {
[ configuration A ]
}
location / {
[ configuration B ]
}
location /documents/ {
[ configuration C ]
}
location ^~ /images/ {
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
[ configuration E ]
}
uri | 结果 |
---|---|
/ | 请求将与配置A匹配 |
/index.html | 请求将与配置B匹配 |
/documents/document.html | 请求将与配置C匹配 |
/images/1.gif | 请求将与配置D匹配 |
/documents/1.jpg | 请求将与配置E匹配 |
location / {
default_type text/html;
return 200 "location /";
}
nginx日志
http://nginx.org/en/docs/ngx_core_module.html#error_log
错误日志
Syntax: error_log file [level];
Default: error_log logs/error.log error;
Context: main, http, mail, stream, server, location
访问日志
ngx_http_log_module
log_format
Syntax: log_format name [escape=default|json|none] string …;
Default: log_format combined “…”;
Context: http
access_log
Syntax: access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
access_log off;
Default: access_log logs/access.log combined;
Context: http, server, location, if in location, limit_except
log_format compression '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" "$gzip_ratio"';
access_log /spool/logs/nginx-access.log compression buffer=32k;
日志变量 | 含义 |
---|---|
$remote_addr | 直接客户端地址 |
$http_x_forwarded_for | 间接客户端地址(一般前面会有代理服务器) |
$remote_user | 远程客户端用户名称 |
$time_local | 记录访问时间与时区 |
$request | 用户的请求,使用的http协议 |
$status | 返回状态,200,404,304等 |
$body_bytes_sents | 发送的body字节数 |
$http_referer | 引用页(从哪个链接访问来的) |
$http_user_agent | 客户端 |
-
$bytes_sent
the number of bytes sent to a client
发送给客户端的字节数 -
$connection
connection serial number
连接序列号 -
$connection_requests
the current number of requests made through a connection (1.1.18)
当前通过连接发出的请求数 -
$msec
time in seconds with a milliseconds resolution at the time of the log write
日志写入时的时间(以毫秒为单位) -
$pipe
“p” if request was pipelined, “.” otherwise
“p”(如果请求已传递),否则为"" -
$request_length
request length (including request line, header, and request body)
请求长度(包括请求行,标头和请求正文) -
$request_time
request processing time in seconds with a milliseconds resolution; time elapsed between the first bytes were read from the client and the log write after the last bytes were sent to the client
以毫秒为单位请求处理时间,以毫秒为单位;从客户端读取第一个字节到将最后一个字节发送到客户端后的日志写入之间经过的时间 -
$status
response status
响应状态 -
$time_iso8601
local time in the ISO 8601 standard format
ISO 8601标准格式的当地时间 -
$time_local
local time in the Common Log Format
通用日志格式的本地时间
daemon
Syntax: daemon on | off;
Default: daemon on;
Context: main
nginx选项
-c file Use an alternative configuration file.
-g directives Set global configuration directives. See EXAMPLES for details.
-p prefix Set the prefix path. The default value is /etc/nginx.
-q Suppress non-error messages during configuration testing.
-s signal Send a signal to the master process. The argument signal can be one of: stop, quit, reopen, reload. The fol‐
lowing table shows the corresponding system signals:
stop SIGTERM
quit SIGQUIT
reopen SIGUSR1
reload SIGHUP
-t Do not run, just test the configuration file. nginx checks the configuration file syntax and then tries to
open files referenced in the configuration file.
-V show version and configure options then exit
fastcgi
http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html
ngx_http_fastcgi_module
fastcgi_pass
Syntax: fastcgi_pass address;
Default: —
Context: location, if in location
Sets the address of a FastCGI server. The address can be specified as a domain name or IP address, and a port:
fastcgi_pass localhost:9000;
or as a UNIX-domain socket path:
fastcgi_pass unix:/tmp/fastcgi.socket;
fastcgi_index
http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html
Syntax: fastcgi_index name;
Default: —
Context: http, server, location
fastcgi_index index.php;
fastcgi_param
Syntax: fastcgi_param parameter value [if_not_empty];
Default: —
Context: http, server, location
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
$document_root
root or alias directive’s value for the current request
$fastcgi_script_name
request URI or, if a URI ends with a slash, request URI with an index file name configured by the fastcgi_index directive appended to it. This variable can be used to set the SCRIPT_FILENAME and PATH_TRANSLATED parameters that determine the script name in PHP. For example, for the “/info/” request with the following directives
php连接MySQL测试
https://secure.php.net/manual/zh/function.mysqli-connect.php
<?php
$mysqli = new mysqli("172.16.1.7", "wordpress", "123456");
if(!$mysqli) {
echo"database error";
}else{
echo"php env successful";
}
$mysqli->close();
?>
client_max_body_size
Sets the maximum allowed size of the client request body
设置客户端请求正文的最大允许大小
如果请求中的大小超过配置的值,则会向客户端返回413(请求实体太大)错误
Syntax: client_max_body_size size;
Default: client_max_body_size 1m;
Context: http, server, location
nginx代理
ngx_http_proxy_module
http://nginx.org/en/docs/http/ngx_http_proxy_module.html
location / {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
proxy_pass
Syntax: proxy_pass URL;
Default: —
Context: location, if in location, limit_except
proxy_set_header
Syntax: proxy_set_header field value;
Default: proxy_set_header Host $proxy_host;
proxy_set_header Connection close;
Context: http, server, location
proxy_set_header Host $http_host;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection close;
ngx_http_proxy_module模块支持嵌入式变量,可使用proxy_set_header指令来构成标头
$proxy_add_x_forwarded_for
"X-Forwarded-For"客户端请求标头字段中$remote_addr附加了变量,并用逗号分隔。如果客户端请求标头中不存在"X-Forwarded-For"字段,则该$proxy_add_x_forwarded_for变量等于该$remote_addr变量。
proxy_http_version
Syntax: proxy_http_version 1.0 | 1.1;
Default: proxy_http_version 1.0;
Context: http, server, location
This directive appeared in version 1.1.4.
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_connect_timeout
Syntax: proxy_connect_timeout time;
Default: proxy_connect_timeout 60s;
Context: http, server, location
proxy_read_timeout
Syntax: proxy_read_timeout time;
Default: proxy_read_timeout 60s;
Context: http, server, location
proxy_send_timeout
Syntax: proxy_send_timeout time;
Default: proxy_send_timeout 60s;
Context: http, server, location
proxy_buffer_size
Syntax: proxy_buffer_size size;
Default: proxy_buffer_size 4k|8k;
Context: http, server, location
proxy_buffering
Syntax: proxy_buffering on | off;
Default: proxy_buffering on;
Context: http, server, location
proxy_buffers
Syntax: proxy_buffers number size;
Default: proxy_buffers 8 4k|8k;
Context: http, server, location
uwsgi
http://nginx.org/en/docs/http/ngx_http_uwsgi_module.html
ngx_http_uwsgi_module
uwsgi_pass
location / {
include uwsgi_params;
uwsgi_pass localhost:9000;
}
uwsgi_pass localhost:9000;
uwsgi_pass uwsgi://localhost:9000;
uwsgi_pass suwsgi://[2001:db8::1]:9090;
uwsgi_pass unix:/tmp/uwsgi.socket;
uwsgi_param
Syntax: uwsgi_param parameter value [if_not_empty];
Default: —
Context: http, server, location
uwsgi_param QUERY_STRING $query_string;
uwsgi_param REQUEST_METHOD $request_method;
uwsgi_param CONTENT_TYPE $content_type;
uwsgi_param CONTENT_LENGTH $content_length;
uwsgi_param REQUEST_URI $request_uri;
uwsgi_param PATH_INFO $document_uri;
uwsgi_param DOCUMENT_ROOT $document_root;
uwsgi_param SERVER_PROTOCOL $server_protocol;
uwsgi_param REQUEST_SCHEME $scheme;
uwsgi_param HTTPS $https if_not_empty;
uwsgi_param REMOTE_ADDR $remote_addr;
uwsgi_param REMOTE_PORT $remote_port;
uwsgi_param SERVER_PORT $server_port;
uwsgi_param SERVER_NAME $server_name;
uwsgi_param UWSGI_SCRIPT *.wsgi;
uwsgi_param UWSGI_CHDIR /path;
http2
http://nginx.org/en/docs/http/ngx_http_v2_module.html
ngx_http_v2_module
ngx_http_realip_module
http://nginx.org/en/docs/http/ngx_http_realip_module.html
将客户端地址和可选端口更改为在指定的标头字段中发送的客户端地址和可选端口
默认情况下未构建此模块,应使用–with-http_realip_module 配置参数启用它
set_real_ip_from 192.168.1.0/24;
set_real_ip_from 192.168.2.1;
set_real_ip_from 2001:0db8::/32;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
nginx负载均衡
将请求传递到另一台服务器
ngx_http_upstream_module
http://nginx.org/en/docs/http/ngx_http_upstream_module.html
upstream
Syntax: upstream name { ... }
Default: —
Context: http
server
Syntax: server address [parameters];
Default: —
Context: upstream
[parameters]
weight=number
设置服务器的权重,默认情况下为1
max_conns=number
限制number到代理服务器的同时活动连接的最大数量(1.11.5)。默认值为零,表示没有限制。如果服务器组未驻留在共享内存中,则此限制在每个工作进程中均有效。
如果启用了空闲的keepalive连接,多个worker和共享内存,则到代理服务器的活动和空闲连接总数可能会超过该max_conns值。
max_fails=number
设置在fail_timeout 参数设置的持续时间内应与服务器通信失败的尝试次数,以认为服务器在fail_timeout参数设置的持续时间内不可用 。默认情况下,未成功尝试的次数设置为1。零值将禁用对尝试的记帐。认为失败的尝试由 proxy_next_upstream, fastcgi_next_upstream, uwsgi_next_upstream, scgi_next_upstream, memcached_next_upstream和 grpc_next_upstream 指令定义。
fail_timeout=time
在指定次数的不成功尝试与服务器通信的时间内应该碰巧认为服务器不可用;
以及服务器将被视为不可用的时间段。
默认情况下,该参数设置为10秒。
backup
将服务器标记为备份服务器。当主服务器不可用时,将传递请求。
该参数不能与 hash,ip_hash和随机 负载平衡方法一起使用。
down
将服务器标记为永久不可用
upstream backend {
server backend1.example.com weight=5;
server 127.0.0.1:8080 max_fails=3 fail_timeout=30s;
server unix:/tmp/backend3;
server backup1.example.com backup;
}
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com:8080;
server unix:/tmp/backend3;
server backup1.example.com:8080 backup;
server backup2.example.com:8080 backup;
}
server {
location / {
proxy_pass http://backend;
}
}
负载均衡调度算法
hash
Syntax: hash key [consistent];
Default: —
Context: upstream
This directive appeared in version 1.7.2.
在该服务器组中,客户端-服务器映射基于散列key值。该key可以包含文本,变量,以及它们的组合
ip_hash
Syntax: ip_hash;
Default: —
Context: upstream
根据客户端IP地址在服务器之间分配请求 客户端IPv4地址的前三个八位位组或整个IPv6地址用作哈希密钥。该方法确保了来自同一客户端的请求将始终传递到同一服务器,除非该服务器不可用。在后一种情况下,客户端请求将传递到另一台服务器。最有可能的是,它也将永远是同一台服务器。
keepalive
Syntax: keepalive connections;
Default: —
Context: upstream
This directive appeared in version 1.1.4.
该connections参数设置每个工作进程的高速缓存中保留的到上游服务器的空闲保持连接的最大数量。如果超过此数量,则关闭最近最少使用的连接
upstream http_backend {
server 127.0.0.1:8080;
keepalive 16;
}
server {
...
location /http/ {
proxy_pass http://http_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
...
}
}
keepalive_timeout
Syntax: keepalive_timeout timeout;
Default: keepalive_timeout 60s;
Context: upstream
This directive appeared in version 1.15.3.
设置一个超时,在此超时期间,与上游服务器的空闲keepalive连接将保持打开状态。
keepalive_requests
Syntax: keepalive_requests number;
Default: keepalive_requests 100;
Context: upstream
This directive appeared in version 1.15.3.
设置通过一个keepalive连接可以处理的最大请求数。发出最大数量的请求后,将关闭连接。
least_conn
Syntax: least_conn;
Default: —
Context: upstream
This directive appeared in versions 1.3.1 and 1.2.2.
将请求传递到活动连接数最少的服务器,同时考虑服务器的权重
least_time
Syntax: least_time header | last_byte [inflight];
Default: —
Context: upstream
This directive appeared in version 1.7.10.
将请求传递到服务器的平均响应时间最短且活动连接数最少,同时考虑服务器的权重
random
Syntax: random [two [method]];
Default: —
Context: upstream
This directive appeared in version 1.15.1.
将请求传递到随机选择的服务器,同时考虑服务器的权重
sticky
Syntax: sticky cookie name [expires=time] [domain=domain] [httponly] [secure] [path=path];
sticky route $variable ...;
sticky learn create=$variable lookup=$variable zone=name:size [timeout=time] [header] [sync];
Default: —
Context: upstream
This directive appeared in version 1.5.7.
同一客户端的请求传递到一组服务器中的同一服务器
upstream backend {
server backend1.example.com;
server backend2.example.com;
sticky cookie srv_id expires=1h domain=.example.com path=/;
}
session共享
安装php连接redis模块
yum install php71-php-pecl-redis
/etc/php.ini
session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379?weight=2&timeout=2.5"
php-fpm.d/www.conf (注释session)
...
;php_value[session.save_handler] = files
;php_value[session.save_path] = /var/opt/remi/php71/lib/php/session
使用uri做网站分离
网站准备
agent.wuxing.com.conf(web01)
server {
listen 8081;
server_name agent.wuxing.com;
location / {
root /agent/8081;
index index.html;
}
}
server {
listen 8082;
server_name agent.wuxing.com;
location / {
root /agent/8082;
index index.html;
}
}
agent.wuxing.com.conf(web02)
server {
listen 8083;
server_name agent.wuxing.com;
location / {
root /agent/8083;
index index.html;
}
}
server {
listen 8084;
server_name agent.wuxing.com;
location / {
root /agent/8084;
index index.html;
}
}
网站分离
proxy_agent.wuxing.com.conf
upstream user_pool {
server 172.16.1.7:8081;
server 172.16.1.7:8082;
}
upstream pass_pool {
server 172.16.1.8:8083;
server 172.16.1.8:8084;
}
server {
listen 80;
server_name agent.wuxing.com;
location /user {
proxy_pass http://user_pool/;
include proxy_params;
}
location /pass {
proxy_pass http://pass_pool/;
include proxy_params;
}
}
/etc/nginx/proxy_params
proxy_redirect default;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_buffer_size 32k;
proxy_buffering on;
proxy_buffers 4 128k;
proxy_busy_buffers_size 256k;
proxy_max_temp_file_size 256k;
网站动静分离
安装tomcat
yum install tomcat
jsp页面
webapps/ROOT/index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<head>
<title>Nginx+Tomcat动静分离</title>
</head>
<body>
<%
Random rand = new Random();
out.println("<h2>动态资源</h2>");
out.println(rand.nextInt(99)+100);
%>
<h2>静态图片</h2>
<img src="nginx.png" />
</body>
</html>
ds.wuxing.com.conf
server {
listen 80;
server_name ds.wuxing.com;
location / {
proxy_pass http://127.0.0.1:8080;
}
location ~* \.(jpg|png|jpeg|gif)$ {
root /image;
}
}
静态资源
/image/nginx.png
rewrite模块
ngx_http_rewrite_module
http://nginx.org/en/docs/http/ngx_http_rewrite_module.html
使用PCRE正则表达式更改请求URI,返回重定向并有条件地选择配置
if
Syntax: if (condition) { ... }
Default: —
Context: server, location
如果为true,则执行括号内指定的该模块指令
变量名;如果变量的值为空字符串或“ 0”,则为false;否则为false
使用“ =”和“ !=”运算符将变量与字符串进行比较;
使用" ~ "(用于区分大小写的匹配)和" ~* "(用于区分大小写的匹配)运算符将变量与正则表达式进行匹配。正则表达式可以包含捕获,这些捕获可用于以后在$1.. $9变量中重用。负运算符“ !~”和“ !~*”也可用。如果正则表达式包含“ }”或“ ;”字符,则整个表达式应用单引号或双引号引起来。
使用“ -f”和“ !-f”运算符检查文件是否存在;
使用“ -d”和“ !-d”运算符检查目录是否存在;
使用“ -e”和“ !-e”运算符检查文件,目录或符号链接是否存在;
使用“ -x”和“ !-x”运算符检查可执行文件。
if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /msie/$1 break;
}
if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
set $id $1;
}
if ($request_method = POST) {
return 405;
}
if ($slow) {
limit_rate 10k;
}
if ($invalid_referer) {
return 403;
}
$http_user_agent ~* "android|iphone|MSIE|Chrome"
url.wuxing.com —> url.wuxing.com/m
url.wuxing.com.conf
server {
listen 80;
server_name url.wuxing.com;
root /url;
if ( $http_user_agent ~* "android|iphone|ipad" ) {
rewrite ^/$ /m redirect;
}
location / {
index index.html;
}
}
url.wuxing.com —> m.wuxing.com
url.wuxing.com.conf
server {
listen 80;
server_name url.wuxing.com;
root /url;
if ( $http_user_agent ~* "android|iphone|ipad" ) {
rewrite ^/$ http://m.wuxing.com redirect;
}
location / {
index index.html;
}
}
server {
listen 80;
server_name m.wuxing.com;
root /url/m;
location / {
index index.html;
}
}
return
Syntax: return code [text];
return code URL;
return URL;
Default: —
Context: server, location, if
rewrite
Syntax: rewrite regex replacement [flag];
Default: —
Context: server, location, if
如果指定的正则表达式与请求URI匹配,则URI将按照replacement字符串中的指定进行更改。该rewrite指令在其在配置文件中出现的顺序顺序地执行。可以使用标志终止指令的进一步处理。如果替换字符串以“ http://”,“ https://”或“ $scheme” 开头,则处理将停止并将重定向返回给客户端。
[flag]
last
停止处理当前ngx_http_rewrite_module指令集, 并开始搜索与更改后的URI相匹配的新位置;
break
ngx_http_rewrite_module与break指令一样, 停止处理所有指令集;
redirect
返回带有302代码的临时重定向;如果替换字符串不是以“ http://”,“ https://”或“ $scheme” 开头,则使用
permanent
返回带有301代码的永久重定向。
server {
...
rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;
rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra last;
return 403;
...
}
location /download/ {
rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 break;
rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra break;
return 403;
}
break
Syntax: break;
Default: —
Context: server, location, if
if ($slow) {
limit_rate 10k;
break;
}
停止处理当前ngx_http_rewrite_module指令集 。
如果在location内指定了伪指令,则 在此位置继续进行请求的进一步处理。
set
Syntax: set $variable value;
Default: —
Context: server, location, if
value为指定的 设置variable。该value可以包含文本,变量,他们的组合
url.wuxing.conf
server {
listen 80;
server_name url.wuxing.cn url.wuxing.jp;
if ($http_host ~* "cn") {
set $lang "/zh";
}
if ($http_host ~* "jp") {
set $lang "jp";
}
root /code/$lang;
location / {
index index.html;
}
}
url2.wuxing.com.conf
server {
listen 80;
server_name url.wuxing.com;
if ($http_accept_language ~* "^zh") {
set $domain "zh";
}
if ($http_accept_language ~* "^en") {
set $domain "en";
}
root /url/$domain;
location / {
index index.html;
}
}
http_ssl
ngx_http_ssl_module
http://nginx.org/en/docs/http/ngx_http_ssl_module.html
ngx_http_ssl_module模块为HTTPS提供必要的支持
默认情况下未构建此模块,应使用–with-http_ssl_module 配置参数启用它
http {
...
server {
listen 443 ssl;
server_name test.wuxingge.com;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers AES128-SHA:AES256-SHA:RC4-SHA:DES-CBC3-SHA:RC4-MD5;
ssl_certificate /usr/local/nginx/conf/cert.pem;
ssl_certificate_key /usr/local/nginx/conf/cert.key;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
...
}
server {
listen 80;
server_name test.wuxing.com;
return 302 https://$http_host$request_uri;
}
}
openssl genrsa -idea -out server.key 2048
openssl req -days 36500 -x509 -sha256 -nodes -newkey rsa:2048 -keyout server.key -out server.crt
openssl req -nodes -newkey rsa:2048 -keyout server.key -out server.csr -subj "/C=/ST=/L=/O=/OU=/CN=wuxing"
openssl x509 -req -sha256 -days 36500 -in server.csr -signkey server.key -out server.crt
openssl
https://www.openssl.org/docs/manmaster/man1/openssl.html
openssl genrsa --help
usage: genrsa [args] [numbits]
-des encrypt the generated key with DES in cbc mode
-des3 encrypt the generated key with DES in ede cbc mode (168 bit key)
-idea encrypt the generated key with IDEA in cbc mode
-seed
encrypt PEM output with cbc seed
-aes128, -aes192, -aes256
encrypt PEM output with cbc aes
-camellia128, -camellia192, -camellia256
encrypt PEM output with cbc camellia
-out file output the key to 'file
-passout arg output file pass phrase source
-f4 use F4 (0x10001) for the E value
-3 use 3 for the E value
-engine e use engine e, possibly a hardware device.
-rand file:file:...
load the file (or the files in the directory) into
the random number generator
openssl req --help
unknown option --help
req [options] <infile >outfile
where options are
-inform arg input format - DER or PEM
-outform arg output format - DER or PEM
-in arg input file
-out arg output file
-text text form of request
-pubkey output public key
-noout do not output REQ
-verify verify signature on REQ
-modulus RSA modulus
-nodes don't encrypt the output key
-engine e use engine e, possibly a hardware device
-subject output the request's subject
-passin private key password source
-key file use the private key contained in file
-keyform arg key file format
-keyout arg file to send the key to
-rand file:file:...
load the file (or the files in the directory) into
the random number generator
-newkey rsa:bits generate a new RSA key of 'bits' in size
-newkey dsa:file generate a new DSA key, parameters taken from CA in 'file'
-newkey ec:file generate a new EC key, parameters taken from CA in 'file'
-[digest] Digest to sign with (see openssl dgst -h for list)
-config file request template file.
-subj arg set or modify request subject
-multivalue-rdn enable support for multivalued RDNs
-new new request.
-batch do not ask anything during request generation
-x509 output a x509 structure instead of a cert. req.
-days number of days a certificate generated by -x509 is valid for.
-set_serial serial number to use for a certificate generated by -x509.
-newhdr output "NEW" in the header lines
-asn1-kludge Output the 'request' in a format that is wrong but some CA's
have been reported as requiring
-extensions .. specify certificate extension section (override value in config file)
-reqexts .. specify request extension section (override value in config file)
-utf8 input characters are UTF8 (default ASCII)
-nameopt arg - various certificate name options
-reqopt arg - various request text options
openssl x509 --help
unknown option --help
usage: x509 args
-inform arg - input format - default PEM (one of DER, NET or PEM)
-outform arg - output format - default PEM (one of DER, NET or PEM)
-keyform arg - private key format - default PEM
-CAform arg - CA format - default PEM
-CAkeyform arg - CA key format - default PEM
-in arg - input file - default stdin
-out arg - output file - default stdout
-passin arg - private key password source
-serial - print serial number value
-subject_hash - print subject hash value
-subject_hash_old - print old-style (MD5) subject hash value
-issuer_hash - print issuer hash value
-issuer_hash_old - print old-style (MD5) issuer hash value
-hash - synonym for -subject_hash
-subject - print subject DN
-issuer - print issuer DN
-email - print email address(es)
-startdate - notBefore field
-enddate - notAfter field
-purpose - print out certificate purposes
-dates - both Before and After dates
-modulus - print the RSA key modulus
-pubkey - output the public key
-fingerprint - print the certificate fingerprint
-alias - output certificate alias
-noout - no certificate output
-ocspid - print OCSP hash values for the subject name and public key
-ocsp_uri - print OCSP Responder URL(s)
-trustout - output a "trusted" certificate
-clrtrust - clear all trusted purposes
-clrreject - clear all rejected purposes
-addtrust arg - trust certificate for a given purpose
-addreject arg - reject certificate for a given purpose
-setalias arg - set certificate alias
-days arg - How long till expiry of a signed certificate - def 30 days
-checkend arg - check whether the cert expires in the next arg seconds
exit 1 if so, 0 if not
-signkey arg - self sign cert with arg
-x509toreq - output a certification request object
-req - input is a certificate request, sign and output.
-CA arg - set the CA certificate, must be PEM format.
-CAkey arg - set the CA key, must be PEM format
missing, it is assumed to be in the CA file.
-CAcreateserial - create serial number file if it does not exist
-CAserial arg - serial file
-set_serial - serial number to use
-text - print the certificate in text form
-C - print out C code forms
-<dgst> - digest to use, see openssl dgst -h output for list
-extfile - configuration file with X509V3 extensions to add
-extensions - section from config file with X509V3 extensions to add
-clrext - delete extensions before signing and input certificate
-nameopt arg - various certificate name options
-engine e - use engine e, possibly a hardware device.
-certopt arg - various certificate text options
-checkhost host - check certificate matches "host"
-checkemail email - check certificate matches "email"
-checkip ipaddr - check certificate matches "ipaddr"