nginx自定义变量与内置预定义变量(获取GET参数值,HEADER参数值等)

 nginx  nginx自定义变量与内置预定义变量(获取GET参数值,HEADER参数值等)已关闭评论
3月 242021
 

总览
nginx可以使用变量简化配置与提高配置的灵活性,所有的变量值都可以通过这种方式引用:

$变量名

而nginx中的变量分为两种,自定义变量与内置预定义变量

内置变量
声明
可以在sever,http,location等标签中使用set命令(非唯一)声明变量,语法如下

set $变量名 变量值

注意nginx中的变量必须都以$开头。

可见性
nginx的配置文件中所有使用的变量都必须是声明过的,否则nginx会无法启动并打印相关异常日志

nginx变量的一个有趣的特性就是nginx中没一个变量都是全局可见的,而他们又不是全局变量。比如下面这个例子

location a/ {
return 200 $a
}

location b/ {
set $a hello nginx
return 200 $a
}

由于变量是全局可见的所以nginx启动不会报错,而第一个location中并不知道$a的具体值因此返回的响应结果为一个空字符串。

在不同层级的标签中声明的变量性的可见性规则如下:

location标签中声明的变量中对这个location块可见
server标签中声明的变量对server块以及server块中的所有子块可见
http标签中声明的变量对http块以及http块中的所有子块可见
内置预定义变量
内置预定义变量即无需声明就可以使用的变量,通常包括一个http请求或响应中一部分内容的值,以下为一些常用的内置预定义变量

变量名 定义
$arg_PARAMETER GET请求中变量名PARAMETER参数的值。
$args 这个变量等于GET请求中的参数。例如,foo=123&bar=blahblah;这个变量只可以被修改
$binary_remote_addr 二进制码形式的客户端地址。
$body_bytes_sent 传送页面的字节数
$content_length 请求头中的Content-length字段。
$content_type 请求头中的Content-Type字段。
$cookie_COOKIE cookie COOKIE的值。
$document_root 当前请求在root指令中指定的值。
$document_uri 与$uri相同。
$host 请求中的主机头(Host)字段,如果请求中的主机头不可用或者空,则为处理请求的server名称(处理请求的server的server_name指令的值)。值为小写,不包含端口。
$hostname 机器名使用 gethostname系统调用的值
$http_HEADER HTTP请求头中的内容,HEADER为HTTP请求中的内容转为小写,-变为_(破折号变为下划线),例如:$http_user_agent(Uaer-Agent的值);
$sent_http_HEADER HTTP响应头中的内容,HEADER为HTTP响应中的内容转为小写,-变为_(破折号变为下划线),例如: $sent_http_cache_control, $sent_http_content_type…;
$is_args 如果$args设置,值为”?”,否则为””。
$limit_rate 这个变量可以限制连接速率。
$nginx_version 当前运行的nginx版本号。
$query_string 与$args相同。
$remote_addr 客户端的IP地址。
$remote_port 客户端的端口。
$remote_user 已经经过Auth Basic Module验证的用户名。
$request_filename 当前连接请求的文件路径,由root或alias指令与URI请求生成。
$request_body 这个变量(0.7.58+)包含请求的主要信息。在使用proxy_pass或fastcgi_pass指令的location中比较有意义。
$request_body_file 客户端请求主体信息的临时文件名。
$request_completion 如果请求成功,设为”OK”;如果请求未完成或者不是一系列请求中最后一部分则设为空。
$request_method 这个变量是客户端请求的动作,通常为GET或POST。包括0.8.20及之前的版本中,这个变量总为main request中的动作,如果当前请求是一个子请求,并不使用这个当前请求的动作。
$request_uri 这个变量等于包含一些客户端请求参数的原始URI,它无法修改,请查看$uri更改或重写URI。
$scheme 所用的协议,比如http或者是https,比如rewrite ^(.+)$ $scheme://example.com$1 redirect;
$server_addr 服务器地址,在完成一次系统调用后可以确定这个值,如果要绕开系统调用,则必须在listen中指定地址并且使用bind参数。
$server_name 服务器名称。
$server_port 请求到达服务器的端口号。
$server_protocol 请求使用的协议,通常是HTTP/1.0或HTTP/1.1。
$uri 请求中的当前URI(不带请求参数,参数位于a r g s ) , 不 同 于 浏 览 器 传 递 的 args),不同于浏览器传递的args),不同于浏览器传递的request_uri的值,它可以通过内部重定向,或者使用index指令进行修改。不包括协议和主机名,例如/foo/bar.html

原文链接:https://blog.csdn.net/m0_37556444/article/details/84563520

nginx搭建rtmp服务器(原有nginx上添加模块方式)及让nginx支持HLS

 nginx  nginx搭建rtmp服务器(原有nginx上添加模块方式)及让nginx支持HLS已关闭评论
1月 122021
 

转自:https://www.cnblogs.com/HintLee/p/9499429.html

参考:   https://www.jianshu.com/p/089b70f57bca

前言

最近接手了一个跟视频监控相关的项目,用了近年来越来越流行的 Web 服务器 nginx 加上 nginx-rtmp-module 搭建 rtmp 服务器。使用了阿里云的服务器,系统 Ubuntu 16.04 。

步骤

更新源并安装 nginx 。

sudo apt-get update
sudo apt-get install nginx

一、 支持RTMP

输入 nginx -V 查看 nginx 版本,可以看到当前版本号是 1.10.3,且可以看到编译选项。所以下一步要做的是下载相同版本的 nginx 源码,使用相同的编译选项并添加 nginx-rtmp-module,替换原来的 nginx 。
下载 nginx 1.10.3 的源码和 nginx-rtmp-module 的源码。

wget https://nginx.org/download/nginx-1.10.3.tar.gz
tar zxvf nginx-1.10.3.tar.gz
git clone https://github.com/sergey-dryabzhinsky/nginx-rtmp-module.git
cp -r nginx-rtmp-module nginx-1.10.3

在第 3 步中可以得知安装的 nginx 的编译选项,所以套用这些编译选项,在上一步已经把 nginx-rtmp-module 复制到 nginx 源码目录,所以在结尾添加 –add-module=./nginx-rtmp-module 。在 nginx-1.10.3 目录执行以下命令:

./configure --with-cc-opt='-g -O2 -fPIE -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2' --with-ld-opt='-Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now' --prefix=/usr/share/nginx --conf-path=/etc/nginx/nginx.conf --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/run/nginx.pid --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-debug --with-pcre-jit --with-ipv6 --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_auth_request_module --with-http_addition_module --with-http_dav_module --with-http_geoip_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module --with-http_v2_module --with-http_sub_module --with-http_xslt_module --with-stream --with-stream_ssl_module --with-mail --with-mail_ssl_module --with-threads --add-module=./nginx-rtmp-module

上一步执行后可能会提示以下几个错误,需安装相关软件包,然后再次执行步骤 5 的命令。

./configure: error: the HTTP rewrite module requires the PCRE library.
./configure: error: SSL modules require the OpenSSL library.
./configure: error: the HTTP XSLT module requires the libxml2/libxslt
./configure: error: the HTTP image filter module requires the GD library.
./configure: error: the GeoIP module requires the GeoIP library.
sudo apt-get install libpcre3 libpcre3-dev
sudo apt-get install openssl libssl-dev
sudo apt-get install libxml2 libxml2-dev libxslt-dev
sudo apt-get install libgd2-xpm-dev
sudo apt-get install libgeoip-dev

上一步执行完成后 make,等待 nginx 编译完成。编译过程可能会出现 error: macro “DATE” might prevent reproducible builds 错误,在 CFLAGS 中添加 -Wno-error=date-time 参数即可,也就是步骤5的命令改成

./configure --with-cc-opt='-g -O2 -fPIE -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -Wno-error=date-time -D_FORTIFY_SOURCE=2' --with-ld-opt='-Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now' --prefix=/usr/share/nginx --conf-path=/etc/nginx/nginx.conf --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/run/nginx.pid --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-debug --with-pcre-jit --with-ipv6 --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_auth_request_module --with-http_addition_module --with-http_dav_module --with-http_geoip_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module --with-http_v2_module --with-http_sub_module --with-http_xslt_module --with-stream --with-stream_ssl_module --with-mail --with-mail_ssl_module --with-threads --add-module=./nginx-rtmp-module

编译完成后,在 objs 目录下会有 nginx 的可执行文件。首先停止 nginx 服务,替换掉 nginx 。

sudo service nginx stop
cd /usr/sbin
sudo mv nginx nginx.bak
sudo cp ~/nginx-1.10.3/objs/nginx ./

修改 /etc/nginx/nginx.conf,在结尾添加使其开启 nginx-rtmp-module 相关的功能。

rtmp {
        server {
                listen 1935;
                chunk_size 4000;
                application live {
                        live on;
                }
        }
}

执行 sudo service nginx restart 重启 nginx 服务,然后执行 netstat -a|grep 1935,可以看到 1935 端口处于 LISTEN 状态,即可向 nginx 推流。更多强大的功能可以查看 nginx-rtmp-module

 

二、 支持HLS

找到rtmp 修改下面这个地方

rtmp {
    server {
        listen 1935;
        application live {
            live on;
            record off;
        }
 
        # HLS
 
        # For HLS to work please create a directory in tmpfs (/tmp/hls here)
        # for the fragments. The directory contents is served via HTTP (see
        # http{} section in config)
        #
        # Incoming stream must be in H264/AAC. For iPhones use baseline H264
        # profile (see ffmpeg example).
        # This example creates RTMP stream from movie ready for HLS:
        #
        # ffmpeg -loglevel verbose -re -i movie.avi  -vcodec libx264
        #    -vprofile baseline -acodec libmp3lame -ar 44100 -ac 1
        #    -f flv rtmp://localhost:1935/hls/movie
        #
        # If you need to transcode live stream use 'exec' feature.
        #
        application hls {
            live on;
            hls on;
            hls_path /usr/local/var/www/hls;
        }
 
        # MPEG-DASH is similar to HLS
 
        application dash {
            live on;
            dash on;
            dash_path /tmp/dash;
        }
    }
 } 
保存配置文件,重新加载nginx配置

nginx -s reload

2.进行推流测试(使用ffmpeg,安装见最后)

ffmpeg -loglevel verbose -re -i /Data/Movies/Demo.mov  -vcodec libx264 -vprofile baseline -acodec libmp3lame -ar 44100 -ac 1 -f flv rtmp://localhost:1935/hls/movie

然后你就可以在这个目录
/usr/local/var/www/hls
看到生成一个个ts的文件,还会生成一个movie.m3u8的文件

在Safari里输入地址查看视频(需要等movie.m3u8文件生成后),也可以用iPad或者iPhone上的Safari来访问(其他设备记得需要把localhost改为nginx的ip地址)
http://localhost:8080/hls/movie.m3u8

附:
ffmpeg安装:

Ubuntu

Ubuntu 中安装比较简单,直接使用 apt 安装即可

1
$ sudo apt install -y ffmpeg

CentOS

CentOS 中则比较麻烦,需要使用源码安装

下载并解压

1
2
3
$ wget https://ffmpeg.org/releases/ffmpeg-4.1.tar.bz2
$ tar -xjvf ffmpeg-4.1.tar.bz2
$ cd ffmpeg-4.1

编译

1
2
$ ./configure
nasm/yasm not found or too old. Use --disable-x86asm for a crippled build.

可以使用 --disable-x86asm 参数略过该配置或者直接安装

1
$ sudo yum install -y yasm

也可以从官网下载源码安装

随后再次编译安装即可

1
2
$ ./configure
$ sudo make && sudo make install

nginx 403 forbidden, Permission denied 错误处理方法

 nginx  nginx 403 forbidden, Permission denied 错误处理方法已关闭评论
7月 052020
 

nginx配置好后端网站配置文件后,提示 403 forbidden 的问题,这个问题其实是很常见的问题,一般都是由以下4个方面的原因引起的:

 

一、由于启动用户和nginx工作用户不一致所致

1.1查看nginx的启动用户,发现是nobody,而实际用root启动的

ps aux | grep "nginx: worker process" | awk'{print $1}'

1.2将nginx.config的user改为和启动用户一致,

vi conf/nginx.conf

 

二、缺少index.html或者index.php文件,就是配置文件中index index.html index.htm这行中的指定的文件。
    server {
      listen       80;
      server_name  localhost;
      index  index.php index.html;
      root  /data/www/;
    }

如果在/data/www/下面没有index.php,index.html的时候,直接文件,会报403 forbidden。

三、权限问题,如果nginx没有web目录的操作权限,也会出现403错误。

解决办法:修改web目录的读写权限,或者是把nginx的启动用户改成目录的所属用户,重启Nginx即可解决

   chmod -R 777 /data
   chmod -R 777 /data/web/
四、SELINUX设置为开启状态(enabled)的原因。

4.1、查看当前selinux的状态。

    /usr/sbin/sestatus

4.2、将SELINUX=enforcing 修改为 SELINUX=disabled 状态。

    vi /etc/selinux/config

    #SELINUX=enforcing
    SELINUX=disabled

4.3、重启生效。reboot。

    reboot

 

ubuntu下建立nginx自启动服务

 nginx  ubuntu下建立nginx自启动服务已关闭评论
5月 182020
 
一、Nignx中添加服务在服务目录中,/lib/systemd/system
1、 新建一个nginxd.service
[Unit]
Description=nginx
After=network.target
 
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload -c /usr/local/nginx/conf/nginx.conf
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true
 
[Install]
WantedBy=multi-user.target

ExecStart:这句话的作用是 在/usr/local/nginx/sbin/nginx 中查找 nginx.conf 文件。

ExecReload:在/usr/local/nginx/sbin/nginx 中查找 nginx.conf 文件,刷新Nginx配置后重启。

ExecStop :在/usr/local/nginx/sbin/nginx 中停止nginx。

2、修改nginxd.service的权限

可执行权限chmod 755 nginxd.service 现在,在任何路径下 ,都可以直接使用nginx服务了。

systemctl daemon-reload :重载服务

systemctl status nginxd :查看 nginxd服务状态

systemctl restart nginxd.service :重启nginx服务

注意

1、systemctl status nginxd 中 nginxd 写成 nginxd.service 也可以。

2、如果不能够在windos中访问,参见【二、防火墙状态】,即关闭防火墙 或者在防火墙文件中配置这个端口。

二、防火墙状态

如果我们把防火墙停掉: systemctl stop iptables,那么任何外部的机器都能直接来访问服务器,而服务器也可以没有任何限制的去访问外部资源。相当于,防火墙是一个屏障,现在没有这个屏障了,双方可以互相沟通。

注意:systemctl disable iptables : 防火墙 永久不跟随系统启动而启动。即开机不自启动

systemctl start iptables : 启动防火墙

systemctl status iptables :查看防火墙状态

systemctl stop iptables : 停止防火墙 或者我们不关闭防火墙,那就需要我们在防火墙中把Nginx配置的端口打开。

防火墙默认地址:/etc/sysconfig/iptables在这个文件中添加这句话

-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT

 

参考: https://www.jianshu.com/p/8a94a12b37bc

Nginx配置basic_auth密码验证

 nginx  Nginx配置basic_auth密码验证已关闭评论
4月 292020
 

网上找到的一篇文章描述nginx配置basic_auth的,来自以下链接https://www.centos.bz/2017/07/nginx-basic_auth-password/

 

Nginx添加basic_auth,意思就是访问页面的时候需要弹出来一个用户和密码验证的东西,本文基于CentOS 6

1. 安装密码生成工具htpasswd并生成用户密码文件

yum install httpd-tools               #适用centos
sudo apt-get install apache2-utils    #适用ubuntu

生成用户密码文件

$ htpasswd -c /export/servers/.htpasswd user1  #回车会要求输入两遍密码,会清除所有用户!
$ htpasswd -bc /export/servers/.htpasswd user1 password  #不用回车,直接指定user1的密码为password
$ htpasswd -b /export/servers/.htpasswd user2 password   #添加一个用户,如果用户已存在,则是修改密码
$ htpasswd -D /export/servers/.htpasswd user2  #删除用户

2. 为Nginx添加basic_auth配置

server {
    listen        80;
#    root        /tmp;
#    index        index.html index.htm;
    server_name    o-u-u.com;

    location / {
        auth_basic        "input you user name and password";
        auth_basic_user_file    /export/servers/.htpasswd;
        proxy_pass http://127.0.0.1:9000;
    }
}

然后再次访问o-u-u.com时便会弹出验证框要求输入用户名和密码。

3. 可能遇到的问题

访问o-u-u.com没有弹出验证框怎么办?
首先修改nginx.conf,将日志级别调为info,如下

$ cat /export/servers/nginx-1.12.1/conf/nginx.conf
.......
user  admin;
worker_processes  8;

error_log  logs/error.log info;
......

然后再次访问让其产error_log
看到error_log时会发现有如下错误产生

*69 no user/password was provided for basic authentication, client: 10.12.138.126, server: www.zhukun.net, request: "GET /date_lateral HTTP/1.1", host: "www.zhukun.net"

原因在于

The HTTP Basic authentication works as following:
*) A browser requests a page without user/password.
*) A server response with 401 page, sending realm as well.
   At this stage the 401 code appears in access_log and the message
   “no user/password …” appears in error_log.
*) The browser shows a realm/login/password prompt.
*) If a user will press cancel, then the browser will show the received
   401 page.
*) If the user enters login/password, then the browser repeats the request
   with login/password.

Then until you will exit the browser, it will send these login/password
with all requests in protected hierarchy.

error_page配置的401页面不存在或者指向问题导致的,可以注释掉401配置或者保证401配置指向的文件可用,然后basic_auth便会生效。

Nginx配置文件nginx.conf中文详解

 nginx  Nginx配置文件nginx.conf中文详解已关闭评论
2月 022018
 

实例来自:http://www.cnblogs.com/hunttown/p/5759959.html

######Nginx配置文件nginx.conf中文详解#####

#定义Nginx运行的用户和用户组
user www www;

#nginx进程数,建议设置为等于CPU总核心数。
worker_processes 8;
 
#全局错误日志定义类型,[ debug | info | notice | warn | error | crit ]
error_log /usr/local/nginx/logs/error.log info;

#进程pid文件
pid /usr/local/nginx/logs/nginx.pid;

#指定进程可以打开的最大描述符:数目
#工作模式与连接数上限
#这个指令是指当一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(ulimit -n)与nginx进程数相除,但是nginx分配请求并不是那么均匀,所以最好与ulimit -n 的值保持一致。
#现在在linux 2.6内核下开启文件打开数为65535,worker_rlimit_nofile就相应应该填写65535。
#这是因为nginx调度时分配请求到进程并不是那么的均衡,所以假如填写10240,总并发量达到3-4万时就有进程可能超过10240了,这时会返回502错误。
worker_rlimit_nofile 65535;

events
{
    #参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型
    #是Linux 2.6以上版本内核中的高性能网络I/O模型,linux建议epoll,如果跑在FreeBSD上面,就用kqueue模型。
    #补充说明:
    #与apache相类,nginx针对不同的操作系统,有不同的事件模型
    #A)标准事件模型
    #Select、poll属于标准事件模型,如果当前系统不存在更有效的方法,nginx会选择select或poll
    #B)高效事件模型
    #Kqueue:使用于FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0 和 MacOS X.使用双处理器的MacOS X系统使用kqueue可能会造成内核崩溃。
    #Epoll:使用于Linux内核2.6版本及以后的系统。
    #/dev/poll:使用于Solaris 7 11/99+,HP/UX 11.22+ (eventport),IRIX 6.5.15+ 和 Tru64 UNIX 5.1A+。
    #Eventport:使用于Solaris 10。 为了防止出现内核崩溃的问题, 有必要安装安全补丁。
    use epoll;

    #单个进程最大连接数(最大连接数=连接数*进程数)
    #根据硬件调整,和前面工作进程配合起来用,尽量大,但是别把cpu跑到100%就行。每个进程允许的最多连接数,理论上每台nginx服务器的最大连接数为。
    worker_connections 65535;

    #keepalive超时时间。
    keepalive_timeout 60;

    #客户端请求头部的缓冲区大小。这个可以根据你的系统分页大小来设置,一般一个请求头的大小不会超过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。
    #分页大小可以用命令getconf PAGESIZE 取得。
    #[[email protected] ~]# getconf PAGESIZE
    #4096
    #但也有client_header_buffer_size超过4k的情况,但是client_header_buffer_size该值必须设置为“系统分页大小”的整倍数。
    client_header_buffer_size 4k;

    #这个将为打开文件指定缓存,默认是没有启用的,max指定缓存数量,建议和打开文件数一致,inactive是指经过多长时间文件没被请求后删除缓存。
    open_file_cache max=65535 inactive=60s;

    #这个是指多长时间检查一次缓存的有效信息。
    #语法:open_file_cache_valid time 默认值:open_file_cache_valid 60 使用字段:http, server, location 这个指令指定了何时需要检查open_file_cache中缓存项目的有效信息.
    open_file_cache_valid 80s;

    #open_file_cache指令中的inactive参数时间内文件的最少使用次数,如果超过这个数字,文件描述符一直是在缓存中打开的,如上例,如果有一个文件在inactive时间内一次没被使用,它将被移除。
    #语法:open_file_cache_min_uses number 默认值:open_file_cache_min_uses 1 使用字段:http, server, location  这个指令指定了在open_file_cache指令无效的参数中一定的时间范围内可以使用的最小文件数,如果使用更大的值,文件描述符在cache中总是打开状态.
    open_file_cache_min_uses 1;
    
    #语法:open_file_cache_errors on | off 默认值:open_file_cache_errors off 使用字段:http, server, location 这个指令指定是否在搜索一个文件是记录cache错误.
    open_file_cache_errors on;
}
 
 
 
#设定http服务器,利用它的反向代理功能提供负载均衡支持
http
{
    #文件扩展名与文件类型映射表
    include mime.types;

    #默认文件类型
    default_type application/octet-stream;

    #默认编码
    #charset utf-8;

    #服务器名字的hash表大小
    #保存服务器名字的hash表是由指令server_names_hash_max_size 和server_names_hash_bucket_size所控制的。参数hash bucket size总是等于hash表的大小,并且是一路处理器缓存大小的倍数。在减少了在内存中的存取次数后,使在处理器中加速查找hash表键值成为可能。如果hash bucket size等于一路处理器缓存的大小,那么在查找键的时候,最坏的情况下在内存中查找的次数为2。第一次是确定存储单元的地址,第二次是在存储单元中查找键 值。因此,如果Nginx给出需要增大hash max size 或 hash bucket size的提示,那么首要的是增大前一个参数的大小.
    server_names_hash_bucket_size 128;

    #客户端请求头部的缓冲区大小。这个可以根据你的系统分页大小来设置,一般一个请求的头部大小不会超过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。分页大小可以用命令getconf PAGESIZE取得。
    client_header_buffer_size 32k;

    #客户请求头缓冲大小。nginx默认会用client_header_buffer_size这个buffer来读取header值,如果header过大,它会使用large_client_header_buffers来读取。
    large_client_header_buffers 4 64k;

    #设定通过nginx上传文件的大小
    client_max_body_size 8m;

    #开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。
    #sendfile指令指定 nginx 是否调用sendfile 函数(zero copy 方式)来输出文件,对于普通应用,必须设为on。如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络IO处理速度,降低系统uptime。
    sendfile on;

    #开启目录列表访问,合适下载服务器,默认关闭。
    autoindex on;

    #此选项允许或禁止使用socke的TCP_CORK的选项,此选项仅在使用sendfile的时候使用
    tcp_nopush on;
     
    tcp_nodelay on;

    #长连接超时时间,单位是秒
    keepalive_timeout 120;

    #FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。下面参数看字面意思都能理解。
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;

    #gzip模块设置
    gzip on; #开启gzip压缩输出
    gzip_min_length 1k;    #最小压缩文件大小
    gzip_buffers 4 16k;    #压缩缓冲区
    gzip_http_version 1.0;    #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
    gzip_comp_level 2;    #压缩等级
    gzip_types text/plain application/x-javascript text/css application/xml;    #压缩类型,默认就已经包含textml,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn。
    gzip_vary on;

    #开启限制IP连接数的时候需要使用
    #limit_zone crawler $binary_remote_addr 10m;

    #负载均衡配置
    upstream piao.jd.com {
     
        #upstream的负载均衡,weight是权重,可以根据机器配置定义权重。weigth参数表示权值,权值越高被分配到的几率越大。
        server 192.168.80.121:80 weight=3;
        server 192.168.80.122:80 weight=2;
        server 192.168.80.123:80 weight=3;

        #nginx的upstream目前支持4种方式的分配
        #1、轮询(默认)
        #每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。
        #2、weight
        #指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。
        #例如:
        #upstream bakend {
        #    server 192.168.0.14 weight=10;
        #    server 192.168.0.15 weight=10;
        #}
        #2、ip_hash
        #每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。
        #例如:
        #upstream bakend {
        #    ip_hash;
        #    server 192.168.0.14:88;
        #    server 192.168.0.15:80;
        #}
        #3、fair(第三方)
        #按后端服务器的响应时间来分配请求,响应时间短的优先分配。
        #upstream backend {
        #    server server1;
        #    server server2;
        #    fair;
        #}
        #4、url_hash(第三方)
        #按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。
        #例:在upstream中加入hash语句,server语句中不能写入weight等其他的参数,hash_method是使用的hash算法
        #upstream backend {
        #    server squid1:3128;
        #    server squid2:3128;
        #    hash $request_uri;
        #    hash_method crc32;
        #}

        #tips:
        #upstream bakend{#定义负载均衡设备的Ip及设备状态}{
        #    ip_hash;
        #    server 127.0.0.1:9090 down;
        #    server 127.0.0.1:8080 weight=2;
        #    server 127.0.0.1:6060;
        #    server 127.0.0.1:7070 backup;
        #}
        #在需要使用负载均衡的server中增加 proxy_pass http://bakend/;

        #每个设备的状态设置为:
        #1.down表示单前的server暂时不参与负载
        #2.weight为weight越大,负载的权重就越大。
        #3.max_fails:允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream模块定义的错误
        #4.fail_timeout:max_fails次失败后,暂停的时间。
        #5.backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。

        #nginx支持同时设置多组的负载均衡,用来给不用的server来使用。
        #client_body_in_file_only设置为On 可以讲client post过来的数据记录到文件中用来做debug
        #client_body_temp_path设置记录文件的目录 可以设置最多3层目录
        #location对URL进行匹配.可以进行重定向或者进行新的代理 负载均衡
    }
     
     
     
    #虚拟主机的配置
    server
    {
        #监听端口
        listen 80;

        #域名可以有多个,用空格隔开
        server_name www.jd.com jd.com;
        index index.html index.htm index.php;
        root /data/www/jd;

        #对******进行负载均衡
        location ~ .*.(php|php5)?$
        {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include fastcgi.conf;
        }
         
        #图片缓存时间设置
        location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
        {
            expires 10d;
        }
         
        #JS和CSS缓存时间设置
        location ~ .*.(js|css)?$
        {
            expires 1h;
        }
         
        #日志格式设定
        #$remote_addr与$http_x_forwarded_for用以记录客户端的ip地址;
        #$remote_user:用来记录客户端用户名称;
        #$time_local: 用来记录访问时间与时区;
        #$request: 用来记录请求的url与http协议;
        #$status: 用来记录请求状态;成功是200,
        #$body_bytes_sent :记录发送给客户端文件主体内容大小;
        #$http_referer:用来记录从那个页面链接访问过来的;
        #$http_user_agent:记录客户浏览器的相关信息;
        #通常web服务器放在反向代理的后面,这样就不能获取到客户的IP地址了,通过$remote_add拿到的IP地址是反向代理服务器的iP地址。反向代理服务器在转发请求的http头信息中,可以增加x_forwarded_for信息,用以记录原有客户端的IP地址和原来客户端的请求的服务器地址。
        log_format access ‘$remote_addr – $remote_user [$time_local] “$request” ‘
        ‘$status $body_bytes_sent “$http_referer” ‘
        ‘”$http_user_agent” $http_x_forwarded_for’;
         
        #定义本虚拟主机的访问日志
        access_log  /usr/local/nginx/logs/host.access.log  main;
        access_log  /usr/local/nginx/logs/host.access.404.log  log404;
         
        #对 “/” 启用反向代理
        location / {
            proxy_pass http://127.0.0.1:88;
            proxy_redirect off;
            proxy_set_header X-Real-IP $remote_addr;
             
            #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             
            #以下是一些反向代理的配置,可选。
            proxy_set_header Host $host;

            #允许客户端请求的最大单文件字节数
            client_max_body_size 10m;

            #缓冲区代理缓冲用户端请求的最大字节数,
            #如果把它设置为比较大的数值,例如256k,那么,无论使用firefox还是IE浏览器,来提交任意小于256k的图片,都很正常。如果注释该指令,使用默认的client_body_buffer_size设置,也就是操作系统页面大小的两倍,8k或者16k,问题就出现了。
            #无论使用firefox4.0还是IE8.0,提交一个比较大,200k左右的图片,都返回500 Internal Server Error错误
            client_body_buffer_size 128k;

            #表示使nginx阻止HTTP应答代码为400或者更高的应答。
            proxy_intercept_errors on;

            #后端服务器连接的超时时间_发起握手等候响应超时时间
            #nginx跟后端服务器连接超时时间(代理连接超时)
            proxy_connect_timeout 90;

            #后端服务器数据回传时间(代理发送超时)
            #后端服务器数据回传时间_就是在规定时间之内后端服务器必须传完所有的数据
            proxy_send_timeout 90;

            #连接成功后,后端服务器响应时间(代理接收超时)
            #连接成功后_等候后端服务器响应时间_其实已经进入后端的排队之中等候处理(也可以说是后端服务器处理请求的时间)
            proxy_read_timeout 90;

            #设置代理服务器(nginx)保存用户头信息的缓冲区大小
            #设置从被代理服务器读取的第一部分应答的缓冲区大小,通常情况下这部分应答中包含一个小的应答头,默认情况下这个值的大小为指令proxy_buffers中指定的一个缓冲区的大小,不过可以将其设置为更小
            proxy_buffer_size 4k;

            #proxy_buffers缓冲区,网页平均在32k以下的设置
            #设置用于读取应答(来自被代理服务器)的缓冲区数目和大小,默认情况也为分页大小,根据操作系统的不同可能是4k或者8k
            proxy_buffers 4 32k;

            #高负荷下缓冲大小(proxy_buffers*2)
            proxy_busy_buffers_size 64k;

            #设置在写入proxy_temp_path时数据的大小,预防一个工作进程在传递文件时阻塞太长
            #设定缓存文件夹大小,大于这个值,将从upstream服务器传
            proxy_temp_file_write_size 64k;
        }
         
         
        #设定查看Nginx状态的地址
        location /NginxStatus {
            stub_status on;
            access_log on;
            auth_basic “NginxStatus”;
            auth_basic_user_file confpasswd;
            #htpasswd文件的内容可以用apache提供的htpasswd工具来产生。
        }
         
        #本地动静分离反向代理配置
        #所有jsp的页面均交由tomcat或resin处理
        location ~ .(jsp|jspx|do)?$ {
            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_pass http://127.0.0.1:8080;
        }
         
        #所有静态文件由nginx直接读取不经过tomcat或resin
        location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|
        pdf|xls|mp3|wma)$
        {
            expires 15d; 
        }
         
        location ~ .*.(js|css)?$
        {
            expires 1h;
        }
    }
}
######Nginx配置文件nginx.conf中文详解#####

Nginx配置文件nginx.conf中文详解

 nginx  Nginx配置文件nginx.conf中文详解已关闭评论
9月 292015
 

记录下,以备不时之需

#定义Nginx运行的用户和用户组

user www www;

#nginx进程数,建议设置为等于CPU总核心数。

worker_processes 8;

#全局错误日志定义类型,[ debug | info | notice | warn | error | crit ]

error_log /var/log/nginx/error.log info;

#进程文件

pid /var/run/nginx.pid;

#一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(系统的值ulimit -n)与nginx进程数相除,但是nginx分配请求并不均匀,所以建议与ulimit -n的值保持一致。

worker_rlimit_nofile 65535;

#工作模式与连接数上限

events

{

    #参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,如果跑在FreeBSD上面,就用kqueue模型。

    use epoll;

    #单个进程最大连接数(最大连接数=连接数*进程数)

    worker_connections 65535;

}

#设定http服务器

http

{

    include mime.types; #文件扩展名与文件类型映射表

    default_type application/octet-stream; #默认文件类型

    #charset utf-8; #默认编码

    server_names_hash_bucket_size 128; #服务器名字的hash表大小

    client_header_buffer_size 32k; #上传文件大小限制

    large_client_header_buffers 4 64k; #设定请求缓

    client_max_body_size 8m; #设定请求缓

    sendfile on; #开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。

    autoindex on; #开启目录列表访问,合适下载服务器,默认关闭。

    tcp_nopush on; #防止网络阻塞

    tcp_nodelay on; #防止网络阻塞

    keepalive_timeout 120; #长连接超时时间,单位是秒

    #FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。下面参数看字面意思都能理解。

    fastcgi_connect_timeout 300;

    fastcgi_send_timeout 300;

    fastcgi_read_timeout 300;

    fastcgi_buffer_size 64k;

    fastcgi_buffers 4 64k;

    fastcgi_busy_buffers_size 128k;

    fastcgi_temp_file_write_size 128k;

    #gzip模块设置

    gzip on; #开启gzip压缩输出

    gzip_min_length 1k; #最小压缩文件大小

    gzip_buffers 4 16k; #压缩缓冲区

    gzip_http_version 1.0; #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)

    gzip_comp_level 2; #压缩等级

    gzip_types text/plain application/x-javascript text/css application/xml;

    #压缩类型,默认就已经包含text/html,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn。

    gzip_vary on;

    #limit_zone crawler $binary_remote_addr 10m; #开启限制IP连接数的时候需要使用

    upstream blog.ha97.com {

        #upstream的负载均衡,weight是权重,可以根据机器配置定义权重。weigth参数表示权值,权值越高被分配到的几率越大。

        server 192.168.80.121:80 weight=3;

        server 192.168.80.122:80 weight=2;

        server 192.168.80.123:80 weight=3;

    }

    #虚拟主机的配置

    server{

    

        #监听端口

        listen 80;

        #域名可以有多个,用空格隔开

        server_name www.pythontab.com;

        index index.html index.htm index.php;

        root /data/www/pythontab;

        location ~ .*.(php|php5)?$

        {

            fastcgi_pass 127.0.0.1:9000;

            fastcgi_index index.php;

            include fastcgi.conf;

        }

        #图片缓存时间设置

        location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$

        {

            expires 10d;

        }

        #JS和CSS缓存时间设置

        location ~ .*.(js|css)?$

        {

            expires 1h;

        }

        #日志格式设定

        log_format access ‘$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/pythontab.log access;

        #对 “/” 启用反向代理

        location / {

            proxy_pass http://127.0.0.1:8888;

            proxy_redirect off;

            proxy_set_header X-Real-IP $remote_addr;

            #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP

            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

            #以下是一些反向代理的配置,可选。

            proxy_set_header Host $host;

            client_max_body_size 10m; #允许客户端请求的最大单文件字节数

            client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数,

            proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时)

            proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时)

            proxy_read_timeout 90; #连接成功后,后端服务器响应时间(代理接收超时)

            proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小

            proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k以下的设置

            proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2)

            proxy_temp_file_write_size 64k;

            #设定缓存文件夹大小,大于这个值,将从upstream服务器传

        }

        #设定查看Nginx状态的地址

        location /NginxStatus {

            stub_status on;

            access_log on;

            auth_basic “NginxStatus”;

            auth_basic_user_file conf/htpasswd;

            #htpasswd文件的内容可以用apache提供的htpasswd工具来产生。

        }

        #本地动静分离反向代理配置

        #所有jsp的页面均交由tomcat或resin处理

        location ~ .(jsp|jspx|do)?$ {

            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_pass http://127.0.0.1:8080;

        }

        #所有静态文件由nginx直接读取不经过tomcat或resin

        location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)${ 

            expires 15d; 

        }

        location ~ .*.(js|css)?${ 

            expires 1h; 

        }

    }

}

关于Nginx的return配置小技巧(可模拟状态码及数据返回)

 nginx  关于Nginx的return配置小技巧(可模拟状态码及数据返回)已关闭评论
9月 152015
 

使用Nginx的return配置技巧,可模拟状态码及数据返回。

语法:return http状态码
默认值:无
上下文:server,location,if

该指令将结束执行直接返回http状态码到客户端.

支持的http状态码:200, 204, 400, 402-406, 408, 410, 411, 413, 416 , 500-504,还有非标准的444状态码.

使用方法:

#不符合规则的返回403禁止访问

location /download/ {
    rewrite  ^(/download/.*)/media/(.*)..*$  $1/mp3/$2.mp3  break;
    return   403;
}

小技巧

这些小技巧都是wiki里没有介绍的,而系统却是支持的。

如下配置文件:

server { server_name test.liguangming.com; listen 80; location / { add_header Content-Type "text/plain;charset=utf-8"; return 200 "Your IP Address:$remote_addr"; } } 

执行请求:

curl -i http://test.liguangming.com

返回内容如下:

HTTP/1.1 200 OK Server: nginx/1.0.13 Date: Thu, 10 May 2012 10:01:15 GMT Content-Type: application/octet-stream Content-Length: 30 Connection: keep-alive Content-Type: text/plain;charset=utf-8 Your IP Address:123.128.217.19 

好玩吧,还有呢,比如如下的配置文件:

server { server_name test.liguangming.com; listen 80; location / { return http://liguangming.com/; } } 

执行请求:

curl -i http://test.liguangming.com

返回内容如下:

HTTP/1.1 302 Moved Temporarily
Server: nginx/1.0.13
Date: Thu, 10 May 2012 10:06:58 GMT
Content-Type: text/html
Content-Length: 161
Connection: keep-alive
Location: http://liguangming.com/
Content-Type: text/plain;charset=utf-8 <html> <head><title>302 Found</title></head> <body bgcolor="white"> <center><h1>302 Found</h1></center> <hr><center>nginx/1.0.13</center> </body> </html> 

是个302转向,为什么会这样呢?在nginx的源代码里找到src/http/modules/ngx_http_rewrite_module.c文件, 找到return关键字的解析配置:

{ ngx_string("return"),
  NGX_HTTP_SRV_CONF|NGX_HTTP_SIF_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF
                   |NGX_CONF_TAKE12,
  ngx_http_rewrite_return,
  NGX_HTTP_LOC_CONF_OFFSET,
  0,
  NULL },

看到NGX_CONF_TAKE12,原来return允许接受一个或者两个参数啊.

再接着往下看找到ngx_http_rewrite_return函数:

static char * ngx_http_rewrite_return(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {  ngx_http_rewrite_loc_conf_t  *lcf = conf;  u_char                            *p;  ngx_str_t                         *value, *v;  ngx_http_script_return_code_t     *ret;  ngx_http_compile_complex_value_t   ccv;  ret = ngx_http_script_start_code(cf->pool, &lcf->codes,  sizeof(ngx_http_script_return_code_t));  if (ret == NULL) {  return NGX_CONF_ERROR;  }  value = cf->args->elts;  ngx_memzero(ret, sizeof(ngx_http_script_return_code_t));  ret->code = ngx_http_script_return_code;  p = value[1].data;  ret->status = ngx_atoi(p, value[1].len);  if (ret->status == (uintptr_t) NGX_ERROR) {  if (cf->args->nelts == 2  && (ngx_strncmp(p, "http://", sizeof("http://") - 1) == 0  || ngx_strncmp(p, "https://", sizeof("https://") - 1) == 0  || ngx_strncmp(p, "$scheme", sizeof("$scheme") - 1) == 0))  {  ret->status = NGX_HTTP_MOVED_TEMPORARILY;  v = &value[1];  } else {  ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,  "invalid return code "%V"", &value[1]);  return NGX_CONF_ERROR;  }  } else {  if (cf->args->nelts == 2) {  return NGX_CONF_OK;  }  v = &value[2];  }  ngx_memzero(&ccv, sizeof(ngx_http_compile_complex_value_t));  ccv.cf = cf;  ccv.value = v;  ccv.complex_value = &ret->text;  if (ngx_http_compile_complex_value(&ccv) != NGX_OK) {  return NGX_CONF_ERROR;  }  return NGX_CONF_OK; } 

当一个参数的时候,并不一定要是状态码,如果是一个网址,以http,https,或者与请求相同的协议,就会返回一个302重定向. 相当于:

return 302 http://liguangming.com/; 

第二个参数会作为内容返回,其实这不就是一个简单的原生的echo模块吗? 赶着回去吃饭,匆忙写成的,难免有疏漏,有时间再修改.

转自:http://liguangming.com/nginx-return-tips