Home | 简体中文 | 繁体中文 | 杂文 | 打赏(Donations) | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 知乎专栏 | Search | Email

第 47 章 Nginx


47.1. Installing
47.1.1. Installing by apt-get under the debain/ubuntu
47.1.2. CentOS spawn-fcgi script php-fpm fastcgi backend
47.1.3. installing by source
47.1.4. -V show version and configure options then exit
47.1.5. config test
47.1.6. rotate log log shell /etc/logrotate.d/nginx
47.1.7. CentOS 7
47.2. nginx 配置文件
47.2.1. http 配置
47.2.2. events
47.2.3. gzip CDN支持
47.2.4. server_tokens
47.2.5. ssi
47.2.6. server listen 单域名虚拟主机 ssl 虚拟主机 server_name 配置 root 通过$host智能匹配目录 location expires access autoindex try_files add_header
47.2.7. HTTP2 配置 SSL证书 spdy HTTP2 用户访问 HTTP时强制跳转到 HTTPS
47.2.8. rewrite http get 参数处理 正则取非
47.2.9. upstream 负载均衡 weight 权重配置
47.2.10. fastcgi spawn-fcgi php-fpm
47.2.11. return
47.2.12. Nginx 变量 $host http_user_agent http_referer request_filename request_uri remote_addr http_cookie request_method invalid_referer 自定义变量 if 条件判断
47.3. Proxy
47.3.1. proxy_cache
47.3.2. rewrite + proxy_pass
47.3.3. request_filename + proxy_pass
47.3.4. $request_uri 与 proxy_pass 联合使用
47.3.5. try_files 与 proxy_pass 共用
47.3.6. Proxy 与 SSI
47.3.7. Host
47.3.8. expires
47.3.9. X-Forwarded-For
47.3.10. X-Sendfile
47.3.11. proxy_http_version
47.3.12. proxy_set_header
47.3.13. timeout 超时时间
47.3.14. example upstream 实例 Tomcat 实例 Nginx -> Nginx -> Tomcat Proxy 处理 Cookie Proxy 添加 CORS 头
47.4. Nginx module
47.4.1. stub_status
47.4.2. sub_filter 页面中查找和替换
47.4.3. auth_basic
47.4.4. valid_referers
47.4.5. ngx_http_flv_module
47.4.6. ngx_http_mp4_module
47.4.7. limit_zone
47.4.8. image_filter
47.5. Example
47.5.1. Nginx + Tomcat
47.5.2. 拦截index.html
47.5.3. Session 的 Cookie 域处理
47.6. FAQ
47.6.1. 405 Not Allowed?
47.6.2. 502 Bad Gateway?
47.6.3. 413 Request Entity Too Large
47.6.4. 502 Bad Gateway?
47.6.5. 499 Client Closed Request
47.6.6. proxy_pass
47.6.7. proxy_pass SESSION 丢失问题
47.6.8. [alert] 55785#0: *11449 socket() failed (24: Too many open files) while connecting to upstream
47.6.9. server_name 与 SSI 注意事项
47.6.10. location 跨 document_root 引用,引用 document_root 之外的资源
47.6.11. nginx: [warn] duplicate MIME type "text/html" in /etc/nginx/nginx.conf

47.1. Installing

47.1.1. Installing by apt-get under the debain/ubuntu

$ sudo apt-get install nginx
sudo /etc/init.d/nginx start

47.1.2. CentOS


$releasever 是版本号

$basearch 处理器架构


cat > /etc/yum.repos.d/nginx.repo <<EOF
name=nginx repo


cat > /etc/yum.repos.d/nginx.repo <<EOF
name=nginx repo
yum search nginx
============================================= Matched: nginx =============================================
nginx.x86_64 : high performance web server

yum install -y nginx
chkconfig nginx on
service nginx start spawn-fcgi script

yum -y install spawn-fcgi


移除SOCKET与OPTIONS注释, apache改为nginx

# cat /etc/sysconfig/spawn-fcgi
# You must set some working options before the "spawn-fcgi" service will work.
# If SOCKET points to a file, then this file is cleaned up by the init script.
# See spawn-fcgi(1) for all possible options.
# Example :
OPTIONS="-u apache -g apache -s $SOCKET -S -M 0600 -C 32 -F 1 -P /var/run/spawn-fcgi.pid -- /usr/bin/php-cgi"
chkconfig spawn-fcgi on

starting spawn-fcgi

/etc/init.d/spawn-fcgi start

check port

# netstat -nl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0        *                   LISTEN
tcp        0      0 :::22                       :::*                        LISTEN
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node Path
unix  2      [ ACC ]     STREAM     LISTENING     25282  /var/run/php-fcgi.sock
unix  2      [ ACC ]     STREAM     LISTENING     8227   @/com/ubuntu/upstart

Unix domain socket

location ~ \.php$ { fastcgi_pass unix:/var/run/php-fcgi.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /var/www/nginx-default$fastcgi_script_name; include fastcgi_params; }


/usr/bin/spawn-fcgi -a -p 9000 -u nginx -g nginx -d /www -C 32 -F 1 -P /var/run/spawn-fcgi.pid -f /usr/bin/php-cgi

        location ~ \.php$ {
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /var/www/nginx-default$fastcgi_script_name;
            include        fastcgi_params;
# netstat -tulpn | grep :9000
tcp        0      0    *                   LISTEN      26877/php-cgi
chkconfig nginx on

check config

nginx -t php-fpm

rpm -Uvh http://download.fedora.redhat.com/pub/epel/6/x86_64/epel-release-6-5.noarch.rpm
yum install nginx -y

chkconfig nginx on

check config

nginx -t
yum -y install mysql mysql-server
yum -y install php php-cgi php-mysql php-mbstring php-gd php-fastcgi
yum -y install perl-DBI perl-DBD-MySQL

其他 php-fpm YUM源

rpm --import http://rpms.famillecollet.com/RPM-GPG-KEY-remi
rpm -ivh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
# rpm -Uvh http://centos.alt.ru/repository/centos/6/i386/centalt-release-6-1.noarch.rpm
# yum update fastcgi backend

upstream backend  {
  server   localhost:1234;

fastcgi_pass   backend;

47.1.3. installing by source

cd /usr/local/src/
wget http://www.nginx.org/download/nginx-1.0.6.tar.gz

./configure --prefix=/usr/local/server/nginx \
--with-openssl=/usr/include \
--with-pcre=/usr/include/pcre/ \
--with-http_stub_status_module \
--without-http_memcached_module \
--without-http_fastcgi_module \
--without-http_rewrite_module \
--without-http_map_module \
--without-http_geo_module \

rpm 所使用的编译参数

nginx -V
nginx: nginx version: nginx/1.0.6
nginx: built by gcc 4.4.4 20100726 (Red Hat 4.4.4-13) (GCC)
nginx: TLS SNI support enabled
nginx: configure arguments: --prefix=/etc/nginx/ --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.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwcgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-mail --with-mail_ssl_module --with-file-aio --with-ipv6
# nginx -V
nginx version: nginx/1.2.3
built by gcc 4.4.4 20100726 (Red Hat 4.4.4-13) (GCC)
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx/ --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.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-mail --with-mail_ssl_module --with-file-aio --with-ipv6 --with-cc-opt='-O2 -g'

47.1.4. -V show version and configure options then exit

[root@netkiller tmp]# nginx -v
nginx version: nginx/1.10.1

[root@netkiller tmp]# nginx -V
nginx version: nginx/1.10.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-4) (GCC) 
built with OpenSSL 1.0.1e-fips 11 Feb 2013
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --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.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_geoip_module=dynamic --with-http_perl_module=dynamic --add-dynamic-module=njs-1c50334fbea6/nginx --with-threads --with-stream --with-stream_ssl_module --with-http_slice_module --with-mail --with-mail_ssl_module --with-file-aio --with-ipv6 --with-http_v2_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic'


47.1.5. config test

$ sudo service nginx configtest
Testing nginx configuration: nginx.

47.1.6. rotate log log shell

# cat /srv/bin/rotatelog.sh

# run this script at 0:00

#Nginx Log Path
date_dir=`date +%Y/%m/%d/%H`

mkdir -p ${log_dir}/${date_dir} > /dev/null 2>&1
mv ${log_dir}/access.log ${log_dir}/${date_dir}/access.log
mv ${log_dir}/error.log ${log_dir}/${date_dir}/error.log

kill -USR1 `cat /var/run/nginx.pid`

gzip ${log_dir}/${date_dir}/access.log &
gzip ${log_dir}/${date_dir}/error.log &

# cat /etc/logrotate.d/nginx
/var/log/nginx/*.log {
        rotate 52
        create 640 root adm
                [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`

47.1.7. CentOS 7

rpm -ivh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
yum install -y nginx

cp /etc/nginx/nginx.conf{,.original}

vim /etc/nginx/nginx.conf <<VIM > /dev/null 2>&1
:%s/worker_processes  1;/worker_processes  8;/
:%s/worker_connections  1024;/worker_connections  4096;/
:%s/#gzip/server_tokens off;\r    gzip/

sed -i '4iworker_rlimit_nofile 65530;' /etc/nginx/nginx.conf

systemctl enable nginx
systemctl start nginx			


# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful