Nginx

目录

Nginx

安装所需环境

一. gcc 安装 安装 nginx 需要先将官网下载的源码进行编译,编译依赖 gcc 环境,如果没有 gcc 环境,则需要安装:

yum install gcc-c++

二. PCRE pcre-devel 安装 PCRE(Perl Compatible Regular Expressions) 是一个Perl库,包括 perl 兼容的正则表达式库。nginx 的 http 模块使用 pcre 来解析正则表达式,所以需要在 linux 上安装 pcre 库,pcre-devel 是使用 pcre 开发的一个二次开发库。nginx也需要此库。命令:

yum install -y pcre pcre-devel

三. zlib 安装 zlib 库提供了很多种压缩和解压缩的方式, nginx 使用 zlib 对 http 包的内容进行 gzip ,所以需要在 Centos 上安装 zlib 库。

yum install -y zlib zlib-devel

四. OpenSSL 安装 OpenSSL 是一个强大的安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及 SSL 协议,并提供丰富的应用程序供测试或其它目的使用。 nginx 不仅支持 http 协议,还支持 https(即在ssl协议上传输http),所以需要在 Centos 安装 OpenSSL 库。

yum install -y openssl openssl-devel

官网下载

1.直接下载.tar.gz安装包,地址:https://nginx.org/en/download.html

2.使用wget命令下载(推荐)。确保系统已经安装了wget,如果没有安装,执行 yum install wget 安装。

wget -c https://nginx.org/download/nginx-1.20.2.tar.gz

解压

依然是直接命令:

tar -zxvf nginx-1.20.2.tar.gz
cd nginx-1.20.2

配置

其实在 nginx-1.20.2 版本中你就不需要去配置相关东西,默认就可以了。当然,如果你要自己配置目录也是可以的。 1.使用默认配置

./configure

编译安装

make
make install

查找安装路径:

whereis nginx

Nginx设置成服务并开机自动启动

#查看开机自启项
systemctl list-unit-files | grep enabled

在/etc/init.d下创建文件nginx

[root@localhost ~]# vim /etc/init.d/nginx

其内容参考nginx官方文档

https://www.nginx.com/resources/wiki/start/topics/examples/redhatnginxinit/

#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15
# description:  NGINX is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /etc/nginx/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

nginx="/usr/sbin/nginx"
prog=$(basename $nginx)

NGINX_CONF_FILE="/etc/nginx/nginx.conf"

[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx

lockfile=/var/lock/subsys/nginx

make_dirs() {
   # make required directories
   user=`$nginx -V 2>&1 | grep "configure arguments:.*--user=" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   if [ -n "$user" ]; then
      if [ -z "`grep $user /etc/passwd`" ]; then
         useradd -M -s /bin/nologin $user
      fi
      options=`$nginx -V 2>&1 | grep 'configure arguments:'`
      for opt in $options; do
          if [ `echo $opt | grep '.*-temp-path'` ]; then
              value=`echo $opt | cut -d "=" -f 2`
              if [ ! -d "$value" ]; then
                  # echo "creating" $value
                  mkdir -p $value && chown -R $user $value
              fi
          fi
       done
    fi
}

start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    configtest || return $?
    stop
    sleep 1
    start
}

reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $prog -HUP
    retval=$?
    echo
}

force_reload() {
    restart
}

configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}

rh_status() {
    status $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac

需要注意的配置:

nginx=”/usr/local/nginx/sbin/nginx” //修改成nginx执行程序的路径。

NGINX_CONF_FILE=”/usr/local/nginx/conf/nginx.conf” //修改成nginx.conf文件的路径。

保存后设置文件的执行权限

[root@localhost ~]# chmod a+x /etc/init.d/nginx

至此就可以通过下面指令控制启动停止

/etc/init.d/nginx start
/etc/init.d/nginx stop

上面的方法完成了用脚本管理nginx服务的功能,但是还是不太方便。

先将nginx服务加入chkconfig管理列表:

[root@localhost ~]# chkconfig --add /etc/init.d/nginx

加完这个之后,就可以使用service对nginx进行启动,重启等操作了。

service nginx start
service nginx stop
service nginx restart
systemctl start nginx
systemctl status nginx
systemctl stop nginx

最后设置开机自动启动

[root@localhost ~]# chkconfig nginx on

Nginx设置成服务并开机自动启动(2)

在/etc/rc.d/rc.local文件中加入nginx执行文件

vi /etc/rc.d/rc.local

加入

/usr/local/nginx/sbin/nginx 

注意:vi /etc/rc.d/rc.local默认没有执行的权限,需要授权

chmod +x /etc/rc.d/rc.local

问题:

1. Centos7 配置systemctl的Nginx启动服务,start一直卡着,stop不生效

  • 启动Nginx时一直卡着不动在 Starting nginx (via systemctl):
  • 实际端口是开启了
  • 必须通过Ctrl + C强制关闭
  • 关闭Nginx时,提示成功,但是端口没关闭

查看Nginx 状态日志如下

[root@ecs-90d5-0001 nginx-1.18.0]# systemctl status nginx 
● nginx.service - SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server
   Loaded: loaded (/etc/rc.d/init.d/nginx; bad; vendor preset: disabled)
   Active: inactive (dead) since 三 2021-03-31 10:49:52 CST; 45s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 13078 ExecStart=/etc/rc.d/init.d/nginx start (code=exited, status=0/SUCCESS)
   CGroup: /system.slice/nginx.service
           ├─6340 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
           └─6341 nginx: worker process

3月 31 10:49:39 ecs-90d5-0001 systemd[1]: Starting SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server...
3月 31 10:49:39 ecs-90d5-0001 systemd[1]: Can't open PID file /var/run/nginx.pid (yet?) after start: No such file or directory
3月 31 10:49:52 ecs-90d5-0001 systemd[1]: Stopped SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server.

如上PID文件位置不对,修改PID文件路径即可解决上面问题

解决:修改/etc/init.d/nginx 配置的PID文件路径和nginx.conf文件中的PID路径一致

2. 图片上传限制问题

location / {
            root   html;
            index  index.html index.htm;
   client_max_body_size    2000m; #修改成你需要限制大小
  }

3. Job for nginx.service failed because a configured resource limit was exceeded. See “systemctl status nginx.service” and “journalctl -xe” for details.

1. nginx -t //验证下nginx.conf的配置是否正确
2. 报错信息为:nginx.service - SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server

更改为./nginx -c /etc/local/nginx/conf/nginx.conf方式启动或重启
kill掉./nginx启动的进程,然后再换成service nginx start方式启动

4. nginx不能转发带有下划线的header

nginx默认是过滤掉了带有下划线的变量,如果需要添加带有下划线的请求头,需把

underscores_in_headers 设置为 on,和server 同级

修改了配置文件之后一定要记得重启nginx !!!

nginx -s reload

Nginx配置Https

Nginx配置Https

第一步:Nginx的ssl模块安装

先检查下自己是否存在ssl模块:

进入到你的nginx安装目录下面,我的目录是在(/usr/local/nginx

进入到目录的sbin目录下,输入

#注意这里是大写的V,小写的只显示版本号
./nginx -V  

如果出现 (configure arguments: –with-http_ssl_module), 则已安装

一般情况下都是不存在ssl模块的,接下来进入到你的解压缩后的nginx目录,注意这里不是nginx安装目录,是解压缩后的目录,我的是在(/root/nginx),进入目录后,输入

./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module

接下来执行

make
#切记不要执行make install,否则会重新安装nginx

上述操作执行完成以后,你的目录下会出现objs文件夹,文件夹内存在nginx文件,如图:

image-20210409144720491

接下来使用新的nginx文件替换掉之前安装目录sbin下的nginx,注意这里的替换的时候可以先将之前的文件备份下,停掉nginx服务

./nginx -s stop #停止nginx服务 #替换之前的nginx cp /home/platform/nginx-1.18.0/objs/nginx /usr/local/nginx/sbin/

[root@ecs-90d5-0001 nginx-1.18.0]# cp /home/platform/nginx-1.18.0/objs/nginx /usr/local/nginx/sbin/
cp:是否覆盖"/usr/local/nginx/sbin/nginx"? y

第二步:配置ssl证书

解压缩下载好的证书(证书一般是pem文件和key文件,这里名字可以随便改)

将下载好的证书上上传到服务器,我将证书放在了root目录下的card文件夹

#在root目录下创建card文件夹
cd /root
mkdir card

第三步:进行nginx.conf配置

进入nginx.conf文件下

cd /usr/locla/nginx/conf
#修改nginx.conf文件
vim nginx.conf

然后进行配置,输入:

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
  server {
  #监听443端口
    listen 443;
    #你的域名
    server_name huiblog.top; 
    ssl on;
    #ssl证书的pem文件路径
    ssl_certificate  /root/card/huiblog.top.pem;
    #ssl证书的key文件路径
    ssl_certificate_key /root/card/huiblog.top.key;
    location / {
     proxy_pass  http://公网地址:项目端口号;
    }
}
    server {
        listen 80;
        server_name huiblog.top;
        #将请求转成https
        rewrite ^(.*)$ https://${server_name}$1 permanent;
    }
}

注意:这里需要在安全组中开放443端口。

第四步:重启nginx

nginx -t
service nginx restart

nginx.conf

1.全局块

2.events块

3.http块


worker_processes  1; #值越大,可以支持的并发处理量越多

events {
    worker_connections  1024; #支持最大连接数
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  djfy.djfy365.com;
        
		rewrite ^(.*)$ https://${server_name}$1 permanent;
		
        location / {
            root   html;
            index  index.html index.htm;
        }
        
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
      
    }


    # HTTPS server
    #
    server {
        listen       443 ssl;
        server_name  localhost;

        ssl_certificate      /home/soft/nginx/cert/6507020_djfy.djfy365.com.pem;
        ssl_certificate_key  /home/soft/nginx/cert/6507020_djfy.djfy365.com.key;
        #ssl_certificate      C:/nginx/ssl/6218339_test1.djfy365.com.pem;  #本地的证书
        #ssl_certificate_key  C:/nginx/ssl/6218339_test1.djfy365.com.key; #本地的key
        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;
        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

		location /school {
			proxy_pass http://127.0.0.1:8080/school;
			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  X-Forwarded-Proto  $scheme;
			proxy_set_header  X-Forwarded-Scheme "https";
			root html;
			index index.html index.htm;
		}
		
		location /schoolfront/ {
			#root html;
			root /home/project/school/;
			index index.html index.htm;
		}
		
		location /yr/login/app {
            proxy_pass http://127.0.0.1:8089/login/app;
		}
		
		location /yr {
            proxy_pass http://127.0.0.1:8089;
			proxy_set_header Host $host;
		}
		
		location /miniprogram/upload {
			alias /home/upload/upload;
			index  index.php index.html;
		}
		
		
    }

}

nginx 配置文件说明

client_max_body_size     50m; //文件大小限制,默认1m

client_header_timeout    1m;

client_body_timeout      1m;

proxy_connect_timeout     60s;

proxy_read_timeout      1m;

proxy_send_timeout      1m;
client_max_body_size

限制请求体的大小,若超过所设定的大小,返回413错误。

client_header_timeout

读取请求头的超时时间,若超过所设定的大小,返回408错误。

client_body_timeout

读取请求实体的超时时间,若超过所设定的大小,返回413错误。

proxy_connect_timeout

http请求无法立即被容器(tomcat, netty等)处理,被放在nginx的待处理池中等待被处理。此参数为等待的最长时间,默认为60秒,官方推荐最长不要超过75秒。

proxy_read_timeout

http请求被容器(tomcat, netty等)处理后,nginx会等待处理结果,也就是容器返回的response。此参数即为服务器响应时间,默认60秒。

proxy_send_timeout

http请求被服务器处理完后,把数据传返回给Nginx的用时,默认60秒

匹配优先级

location / {
        	echo "hello xy";
            
        }

        location = /a {
        	echo "=/a ";
            
        }

        location ^~ /a {
        	echo "^~ /a ";
            
        }
        location ~ ^/\w {
        	echo "^\w  ";
            
        }
        location ~ ^/[a-z] {
        	echo "^/[a-z]  ";
            
        }

反向代理

image-20220802105244227

 
        location = /a {
            proxy_pass http://ip;
        }
        location = /b/ {
            proxy_pass http://ip;
        }
        结果
        /a/x -> http://ip/a/x;
        /b/x -> http://ip/x

负载均衡

upstream testx {
		#ip_hash;
		server localhost:83 max_fails=2 fail_timeout=3s;
		server localhost:84 max_fails=2 fail_timeout=3s;
		server localhost:85 backup;
    }
    
    server {
        listen       83;
        server_name  localhost:83;
		location /{
        proxy_pass http://127.0.0.1:8091/rental/;
        
		}
	}
	server {
		listen       84;
		server_name  localhost:84;
		location /{
        proxy_pass http://127.0.0.1:8092/rental/;
		}
	}
	
	server {
		listen       85;
		server_name  localhost:85;
		location /{
        
        proxy_pass http://127.0.0.1:8093/rental/;
		}
	}
	
	server {
        listen       80;
        server_name  jc.djfy365.com;
		location / {
		}
		location /admin{
			alias D://projectView/admin;
			index index.html index.htm;
		}
		location /rental/{
			proxy_pass http://testx/;
		}
		
    }

晋城nginx配置

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
	
	client_header_buffer_size 8k;
	client_max_body_size 20M;
	client_body_buffer_size 300M;
	fastcgi_intercept_errors on;
	
	upstream testx {
		#ip_hash;
		server localhost:83 max_fails=2 fail_timeout=3s;
		server localhost:84 max_fails=2 fail_timeout=3s;
		server localhost:85 backup;
    }
	
	server {
        listen       83;
        server_name  localhost:83;
		location /{
        proxy_pass http://127.0.0.1:8091/rental/;
        
		}
	}
	server {
		listen       84;
		server_name  localhost:84;
		location /{
        proxy_pass http://127.0.0.1:8092/rental/;
		}
	}
	
	server {
		listen       85;
		server_name  localhost:85;
		location /{
        
        proxy_pass http://127.0.0.1:8093/rental/;
		}
	}
    server {
        listen       80;
        server_name  jc.djfy365.com;
		
		location / {
         proxy_pass http://127.0.0.1:8089/;
		 #add_header Access-Control-Allow-Origin *;
		}
		
		
		location /dingding {
			#alias html/dingding;
			alias D://projectView/dingding;
			index index.html index.htm;
		}
		
		location /group {
			#alias html/group;
			alias D://projectView/group;
			index index.html index.htm;
		}
		
		location /admin{
			
			alias D://projectView/admin;
			index index.html index.htm;
		}

		location /jlb {
			alias html/jlb;
			index index.html index.htm;
		}
		
		location /upload/app/ {
			proxy_pass http://10.1.59.240:8082/upload/app/;
		}
		
		location /upload/mini/ {
			proxy_pass http://10.1.59.240:8081/upload/mini/;
		}
		
		location /upload/netroom {
			proxy_pass http://10.1.59.240:8083/upload/netroom/;
		}
		
		location /upload/massdefense/ {
			alias D://upload/massdefense/;
		}
		
		location /upload/article/ {
			alias D://upload/article/;
		}
		
		location /upload/common/ {
			alias D://upload/common/;
		}
		
		location /upload/item/ {
			alias D://upload/item/;
		}
		
		location /upload/suggest/ {
			alias D://upload/suggest/;
		}
		
		#location /article/ {
		#	proxy_pass http://127.0.0.1:8086/;
		#}
		#
		#location /common/ {
		#	proxy_pass http://127.0.0.1:8088/;
		#}
		#
		#location /item/ {
		#	proxy_pass http://127.0.0.1:8090/;
		#}
		#
		#location /massdefense/ {
		#	proxy_pass http://127.0.0.1:8087/;
		#}
		
		#location /rental{
        #proxy_pass http://127.0.0.1:8091/rental;
		#}
		
		location /rental/{
			#proxy_pass http://127.0.0.1:8092/rental;
			proxy_pass http://testx/;
		}
		
		location /rentalcord {
        default_type text/html;
        return 200 "7eaebb02efc90720a3d374a2fc128b43"; # 是检验文件中的内容
    }
    #location /rental{
    #    proxy_redirect off;
    #    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:8082/rental;
    #}
    #访问minio网页路径
    # location /minio/rental {
	#	proxy_pass http://127.0.0.1:9000/rental;
    #    proxy_set_header Host $host;
        
    #}
	# location /minio/jwspic {
    #    proxy_pass http://127.0.0.1:9000/jwspic;
    #    proxy_set_header Host $http_host; 
    
    # }
	 location /minio/ {
		proxy_pass http://127.0.0.1:9000/;
        proxy_set_header Host $host;
        
    }
	 
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

师大nginx配置


打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦