Nginx是一款轻量级的HTTP服务器,采用事件驱动的异步非阻塞处理方式框架,这让其具有极好的IO性能,时常用于服务端的反向代理和负载均衡。
常用命令
使用自定义配置文件启动
nginx -c /opt/nginx/config/nginx.conf
柔和重启
nginx -s reload
优雅停止服务
nginx -s quit
强制停止服务
nginx -s stop
配置文件检查
nginx -t
常用配置
反向代理
server {
listen 80;
server_name localhost;
client_max_body_size 1024M;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host:$server_port;
}
}
负载均衡
upstream test {
server localhost:8080;
server localhost:8081;
}
server {
listen 81;
server_name localhost;
client_max_body_size 1024M;
location / {
proxy_pass http://test;
proxy_set_header Host $host:$server_port;
}
}
http服务器
server {
listen 80;
server_name localhost;
client_max_body_size 1024M;
location / {
root e:\wwwroot;
index index.html;
}
}
动静分离
upstream test{
server localhost:8080;
server localhost:8081;
}
server {
listen 80;
server_name localhost;
location / {
root d:\wwwroot;
index index.html;
}
--所有静态请求都由nginx处理,存放目录为html
location ~ \.(gif|jpg|jpeg|png|bmp|swf|css|js)$ {
root d:\wwwroot;
}
--所有动态请求都转发给tomcat处理
location ~ \.(jsp|do)$ {
proxy_pass http://test;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root d:\wwwroot;
}
}
正向代理
resolver 114.114.114.114 8.8.8.8;
server {
resolver_timeout 5s;
listen 81;
access_log d:\wwwroot\proxy.access.log;
error_log d:\wwwroot\proxy.error.log;
location / {
proxy_pass http://$host$request_uri;
}
}
location ~* \.(gif|jpg|png)$ {
valid_referers none blocked 192.168.0.1;
if ($invalid_referer) {
rewrite ^/ http://$host/logo.png;
}
}
根据文件类型设置过期时间
location ~.*\.css$ {
expires 1d;
break;
}
location ~.*\.js$ {
expires 1d;
break;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
access_log off;
expires 15d;
break;
}
匹配规则
location = / {
[ configuration A ]
}
location / {
[ configuration B ]
}
location /documents/ {
[ configuration C ]
}
location ~ /documents/Abc {
[ configuration CC ]
}
location ^~ /images/ {
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
[ configuration E ]
}
location /images/ {
[ configuration F ]
}
location /images/abc {
[ configuration G ]
}
location ~ /images/abc/ {
[ configuration H ]
}
常见问题
**root**
location /i/ {
root /data/wwwroot;
}
真实的路径是root指定的值加上location指定的值,即/data/wwwroot/i/...
**alias**
location /i/ {
alias /data/wwwroot/;
}
在服务器查找的资源路径是: /data/wwwroot/...
|