Linux操作文档——nginx网站服务


一、Nginx服务安装

1、yum安装

[root@nginx-1 ~]# vim /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
[root@nginx-1 ~]# yum -y install nginx
[root@nginx-1 ~]# systemctl start nginx
[root@nginx-1 ~]# netstat -anpt | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      46650/nginx: master 

2、源码编译安装

Nginx官网:http://nginx.org/en/,下载地址:http://nginx.org/download/,或者是从GitGub网站查找下载。

[root@nginx ~]# yum -y install gcc gcc-c++ make libtool  zlib zlib-devel pcre pcre-devel openssl openssl-devel
[root@nginx ~]# useradd -s /sbin/nologin nginx
[root@nginx ~]# wget http://nginx.org/download/nginx-1.18.0.tar.gz(可选)
[root@nginx ~]# tar zxf /media/nginx-1.18.0.tar.gz -C /usr/src/
[root@nginx ~]# tar zxf /media/ngx_cache_purge-2.3.tar.gz -C /usr/src/
[root@nginx ~]# tar zxf /media/nginx-goodies-nginx-sticky-module-ng-08a395c66e42.tar.gz -C /usr/src/
[root@nginx ~]# cd /usr/src/nginx-1.18.0/
[root@nginx nginx-1.18.0]#  ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module --with-http_realip_module --with-http_ssl_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 --with-pcre --add-module=../ngx_cache_purge-2.3 --with-http_flv_module --add-module=../nginx-goodies-nginx-sticky-module-ng-08a395c66e42 && make && make install
[root@nginx ~]# ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/
[root@nginx ~]# mkdir -p /var/tmp/nginx/client
[root@nginx ~]# chown -R nginx:nginx /var/tmp/nginx/
[root@nginx ~]# vim /etc/init.d/nginx
#!/bin/bash
# chkconfig: 2345 99 20
# description: Nginx Service Control Script
PROG="/usr/local/nginx/sbin/nginx"
PIDF="/usr/local/nginx/logs/nginx.pid"
case "$1" in
 start)
 netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/null
 if [ $? -eq 0 ]
 then
 echo "Nginx service already running."
 else
 $PROG -t &> /dev/null
 if [ $? -eq 0 ] ; then 
 $PROG
 echo "Nginx service start success."
 else
 $PROG -t
 fi
 fi
 ;;
 stop)
 netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/null
 if [ $? -eq 0 ]
 then
 kill -s QUIT $(cat $PIDF)
 echo "Nginx service stop success." 
 else
 echo "Nginx service already stop"
 fi
 ;;
 restart)
 $0 stop
 $0 start
 ;;
 status)
 netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/null
 if [ $? -eq 0 ]
 then
 echo "Nginx service is running."
 else
 echo "Nginx is stop."
 fi
 ;; 
 reload)
 netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/null
 if [ $? -eq 0 ]
 then
 $PROG -t &> /dev/null
 if [ $? -eq 0 ] ; then
 kill -s HUP $(cat $PIDF)
 echo "reload Nginx config success."
 else
 $PROG -t
 fi
 else
 echo "Nginx service is not run." 
 fi 
 ;;
 *)
 echo "Usage: $0 {start|stop|restart|reload}"
 exit 1
esac
[root@nginx ~]# chmod +x /etc/init.d/nginx
[root@nginx ~]# chkconfig --add nginx 
[root@nginx ~]# chkconfig nginx on
[root@nginx ~]# service  nginx  start 
Nginx service start success.
[root@nginx ~]# netstat -anpt | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      7329/nginx: master  
[root@nginx ~]# nginx -v
nginx version: nginx/1.18.0
[root@nginx ~]# nginx -V
nginx version: nginx/1.18.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module --with-http_realip_module --with-http_ssl_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 --with-pcre --add-module=../ngx_cache_purge-2.3 --with-http_flv_module --add-module=../nginx-goodies-nginx-sticky-module-ng-08a395c66e42

二、配置文件 nginx.conf

1、全局配置

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
#user  nobody;          //运行用户
worker_processes  4;          //工作进程数量
worker_cpu_affinity 0001  0010 0100 1000;          //设置cpu粘性(四核)
worker_rlimit_nofile    10240;          //进程的最大打开文件数限制

#error_log  logs/error.log;          //错误日志文件的位置
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;          //PID文件的位置

2、I/0事件配置

events {
    use  epoll;          //使用epoll事件模型
    worker_connections  65535;          //单个worker进程允许客户端最大连接数
}

3、HTTP配置

http {
    include       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  logs/access.log  main;	#访问日志位置
    sendfile        on;	#开启高效传输文件模式
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;    #连接保持超时,单位是秒

    #gzip  on;

    server {	#Web服务的监听配置
        listen       80;    	#监听地址及端口

        server_name  localhost;        #网站名称
        #charset koi8-r; 		#网页的默认字符集(可改为utf-8)
        location / { 		#根目录配置
            root   html;        	#网站根目录的位置,相对于安装目录
            index  index.html index.htm;            #默认首页(索引页)
        }

        error_page   500 502 503 504  /50x.html;		#内部错误的反馈页面

        location = /50x.html {        #错误页面配置
            root   html;
        }
    }
}	

三、服务优化

1、配置反向代理

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
http {
    include       mime.types;
    default_type  application/octet-stream;
upstream backend {
#weight:轮询权值;max_fails:允许请求失败的次数
        server 192.168.1.20:80 weight=1 max_fails=2 fail_timeout=10s;
#fail_timeout:在10s内最多容许2次失败;在经历了2次失败以后,10s内不分配请求到这台服务器
        server 192.168.1.30:80 weight=1 max_fails=2 fail_timeout=10s;
        sticky;
}
......
location / {
            root   html;
            index  index.html index.htm;
            proxy_pass http://backend;
            }
......

2、 proxy 缓存使用

http {
......
	#定义日志输出格式main,local可换为iso8601
	log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"'              
		      '"$upstream_cache_status"';    #记录缓存命中率
    access_log  logs/access.log  main;	#调用日志格式main
    client_max_body_size 10m;    #允许客户端请求的最大单文件字节数
    client_body_buffer_size 128k;    #缓冲区代理缓冲用户端请求的最大字节数
    proxy_connect_timeout 75;    #nginx跟后端服务器连接超时时间(代理连接超时)
    proxy_send_timeout 75;    #后端服务器数据回传时间(代理发送超时)
    proxy_read_timeout 75;    #连接成功后,后端服务器响应时间(代理接收超时)
    proxy_buffer_size 4k;    #设置代理服务器(nginx)保存用户头信息的缓冲区大小
    proxy_buffers 4 32k;    #proxy_buffers缓冲区
    proxy_busy_buffers_size 64k;    #高负荷下缓冲大小
    proxy_temp_file_write_size 64k;    #设定缓存文件夹大小
    proxy_buffering on;    #代理时开启或关闭缓冲后端服务器的响应
    proxy_temp_path /usr/local/nginx/proxy_temp;
    proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2 keys_zone=my-cache:100m inactive=600m max_size=2g;
    server_tokens off;    #隐藏nginx的版本号
    sendfile        on;    #开启高效文件传输模式
......
 location / {

            root   html;    #定义服务器的默认网站根目录位置
            index  index.html index.htm;
            proxy_pass http://backend;    #请求转向backend定义的服务器列表,即反向代理
            proxy_redirect off;    #后端的Web服务器可以通过获取用户真实IP
            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_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;    #增加故障转移
            proxy_cache my-cache;    #引用前面定义的缓存区
            add_header Nginx-Cache $upstream_cache_status;
            proxy_cache_valid 200 304 301 302 8h;    #为不同的响应状态码设置不同的缓存时间
            proxy_cache_valid 404 1m;
            proxy_cache_valid any 1d;
            proxy_cache_key $host$uri$is_args$args;
            expires 30d;
        }
......

3、页面压缩

http {
......
    keepalive_timeout  65;    #keepalive_timeout  0;
    gzip  on;	#开启gzip压缩输出,减少网络传输
    gzip_comp_level 6;    #gzip压缩比
    gzip_http_version 1.1;    #识别http协议的版本
    gzip_proxied  any;    #Nginx作为反向代理的时候启用,any–无条件启用压缩
    gzip_min_length 1k;    #设置允许压缩的页面最小字节数
    gzip_buffers 16 8k;    #设置系统获取几个单位的缓存用于存储gzip的压缩结果数据流
    gzip_types  text/htm;    #匹配mime类型进行压缩
    gzip_vary on;    #不管浏览器支不支持都进行压缩

4、连接超时时间

http {
......
    keepalive_timeout  65;
    tcp_nodelay on;    #防止网络阻塞
    client_header_buffer_size 4k;    #客户端请求头部的缓冲区大小
    open_file_cache max=102400 inactive=20s;    #打开文件指定缓存经过20s后文件没被请求后删除缓存
    open_file_cache_valid 30s;30s    #检查一次缓存的有效信息
    open_file_cache_min_uses 1;    #有一个文件在 inactive 时间内一次没被使用,它将被移除
    client_header_timeout 15;    #设置请求头的超时时间
    client_body_timeout 15;    #设置请求体的超时时间
    reset_timedout_connection on;    #关闭不响应的客户端连接
    send_timeout 15;    #响应客户端超时时间

5、fastcgi 调优

http {
......
    keepalive_timeout  65;    #keepalive_timeout  0;
    fastcgi_connect_timeout 600;    #指定连接到后端 FastCGI 的超时时间
    fastcgi_send_timeout 600;    #向 FastCGI 传送请求的超时时间
    fastcgi_read_timeout 600;    #指定接收 FastCGI 应答的超时时间
    fastcgi_buffer_size 64k;    #指定读取 FastCGI 应答第一部分需要用多大的缓冲区
    fastcgi_buffers 4 64k;    #指定本地需要缓冲 FastCGI 的应答请求的空间大小
    fastcgi_busy_buffers_size 128k;    #建议设置为 fastcgi_buffers 的两倍
    fastcgi_temp_file_write_size 128k;    #在写入 fastcgi_temp_path 时将用多大的数据块,默认两倍
    fastcgi_temp_path /usr/local/nginx/nginx_tmp;    #缓存临时目录
    fastcgi_intercept_errors on;    #允许nginx 使用 error_page 处理错误信息
    fastcgi_cache_path  /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=cache_fastcgi:128m inactive=1d max_size=10g;    #astcgi_cache 缓存目录


	location ~ .*.(php|php5)?$ {
	root html/www;
	fastcgi_pass 127.0.0.1:9000;
	fastcgi_index index.php;
	include fastcgi.conf;
	fastcgi_cache ngx_fcgi_cache; # 缓存FastCGI生成的内容,比如PHP生成的动态内容
	fastcgi_cache_valid 200 302 1h; # 指定http状态码的缓存时间,这里表示将200和302缓存1小时
	fastcgi_cache_valid 301 1d; # 指定http状态码的缓存时间,这里表示将301缓存1天
	fastcgi_cache_valid any 1m; # 指定http状态码的缓存时间,这里表示将其他状态码缓存1分钟
	fastcgi_cache_min_uses 1; # 设置请求几次之后响应被缓存,1表示一次即被缓存
	fastcgi_cache_use_stale error timeout invalid_header http_500; # 定义在哪些情况下使用过期缓存
	fastcgi_cache_key http://$host$request_uri; # 定义 fastcgi_cache 的 key
}

6、expires 缓存调优

        location ~* \.(ico|jpe?g|gif|png|bmp|swf|flv)$ {
            expires 30d;
            #log_not_found off;
            access_log off;
        }
        location ~* \.(js|css)$ {
            expires 7d;
            log_not_found off;
            access_log off;
        }

7、防盗链

        location ~* ^.+\.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
            valid_referers none blocked www.benet.com benet.com;
            if ($invalid_referer) {
            #return 302 http://www.benet.com/img/nolink.jpg;
            return 404;
            break;
            }
            access_log off;
        }

8、nginx索引模块设置

http {
......
    #access_log  logs/access.log  main;
    #创建zone区域名为addr,大小10m,保存客户端的二进制ip
    limit_conn_zone $binary_remote_addr zone=addr:10m;
    #创建zone区域名为one,大小10m,保存客户端的二进制ip,限制请求速率每秒1次
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
......
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
        location /download {
            root /www;
            autoindex on;            #启用索引显示
            charset utf-8,gbk;            #字符编码为中文
            autoindex_exact_size on;            #显示文件大小
            autoindex_localtime on;            #显示文件创建时间
            limit_conn addr 1;            #一个ip同一时间点只允许建立一个连接
            limit_req zone=one burst=5;            #调用请求速率区域,另外设置额外突发5次
        }
        location /status {
            stub_status;        	#启用状态化追踪
            access_log off;            #关闭status的日志记录
            allow 192.168.1.0/24;            #仅允许1.0网段访问
            deny all;            #拒绝其他所有
            auth_basic "input your passwd:";            #用户验证启用描述
            auth_basic_user_file /etc/nginx/.auth_conf;            #用户验证文件路径(需提前创建)
        }

9、nginx的location语法

location [ ] /uri/ { … }说明(优先级从高到低)
=开头表示精确匹配
^~开头表示uri以某个常规字符串开头,理解为匹配 url路径即可
~开头表示区分大小写的正则匹配
~*开头表示不区分大小写的正则匹配
!~ 和 !~*分别为区分大小写不匹配及不区分大小写不匹配的正则
/通用匹配,任何请求都会匹配到。
[root@nginx ~]# vim /etc/nginx/conf.d/default.conf
server {
        listen 80;
        server_name test.benet.com;
		#通用匹配,任何请求都会匹配到
        location / {
        }
        #通用匹配,任何请求都会匹配到
        location ~ \.php$ {
			fastcgi_pass http://127.0.0.1:9000;
		}
		#严格区分大小写,匹配.jsp结尾
        location ~ \.jsp$ {
			proxy_pass http://127.0.0.1:8080;
		}
		#不区分大小写匹配
        location ~* "\.(sql|bak|tgz|tar.gz|.git)$ {
			default_type text/html;
			return 403 "启用访问控制";
		}
}
posted @ 2020-06-13 17:37  高中僧  阅读(48)  评论(0)    收藏  举报