[原创]Nginx反向代理及负载均衡

1、基本命令

# 启动nginx
start nginx.exe # windows
nginx -c /usr/local/nginx/conf/nginx.conf # Linux
# 优雅的停止nginx nginx
-s stop # 立即停止nginx nginx -s quit # 重新打开日志文件 nginx -s reopen # 平滑的重启nginx并重新加载nginx的配置文件 nginx -s reload
# 可以用来修改配置文件之后,测试配置文件是否有语法错误 nginx
-t

2、通过信号量来控制nginx

其实质是通过信号量来对nginx进行控制的,所以也可以通过下面的方式来控制nginx:

kill -INT `cat /usr/local/nginx/logs/nginx.pid`
[root@localhost logs]# kill -INT `cat /usr/local/nginx/logs/nginx.pid`
[root@localhost logs]# ps -elf|grep nginx
0 S root      3843  1306  0  80   0 -  1088 -      16:37 pts/1    00:00:00 grep nginx

 看到nginx的两个进程被我们杀掉了。还有其他的信号量可以使用,分别对应到上面的命令。

kill -HUP pid,  kill -USR1 pid, kill -USR2 pid 等等,总结如下:

1. TERM,INT : Quick shutdown,立即关闭进程,不管他有没有在处理请求;

2. QUIT : Graceful shutdown, 优雅的关闭进程,也就是等到该进程处理的请求都完成之后才关闭;

3. HUP : Configuration reload, start the new worker processes with a new configuration. Gracefully shutdown the old worker processes

4. USR1 : Reopen the log files, 重新打开日志文件,在备份日志按月/日分割日志时用;

5. USR2 : Upgrade Executable on the fly, 平滑的升级;

6. WINCH : Gracefully shutdown the worker processes, 优雅的关闭旧的进程(配合USR2来进行升级);

3、图片请求重写到其他服务器

前台服务器对外使用,其中的图片是由后台管理服务器管理的。同时图片的处理模式是DB保存后台管理服务器的访问路径,文件以流的方式保存在后台管理服务器的某一路径。

在投产使用时,由于公网IP和域名不充足的原因,决定只将前台服务器与域名绑定,后台管理服务器使用IP+端口/域名+端口的形式访问。

为了避免IP和端口及应用名暴露出来,现在使用nginx进行反向代理。

 Nginx配置:

# 将http://pic.candy.com/pic请求重写到http://localhost:8080/back/pic

worker_processes  1;
events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
    
    
    server
	  {
				listen       80;
				server_name pic.candy.com;
				
				
    		access_log  logs/access.log  main;
    
			  # 将http://pic.candy.com/pic请求重写到http://localhost:8080/back/pic
				location ~ ^/pic/(.*).(png|jpg|gif)$
				{
				   rewrite ^/pic/(.*).(png|jpg|gif)$ http://localhost:8080/back/pic/$1.$2 break;
				}
  	}
}
原文地址:https://www.cnblogs.com/Candies/p/6984218.html