一、概述
项目总使用到Nginx的代理转发,学习和整理内容如下,由于是整理所以参考博客大牛的内容,有很多雷同之处,还望见谅(非抄袭对待)
二、Nginx依赖包的安装
yum install gcc yum install pcre-devel yum install zlib zlib-devel yum install openssl openssl-devel //一键安装上面四个依赖 yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel
三、安装Nginx
下载:
//创建一个文件夹 cd /usr/local mkdir nginx cd nginx //下载tar包 wget http://nginx.org/download/nginx-1.13.7.tar.gz tar -xvf nginx-1.13.7.tar.g
安装
//进入nginx目录 cd /usr/local/nginx //执行命令 ./configure //执行make命令 make //执行make install命令 make install
Nginx常用命令
cd /user/local/nginx/config #配置文件路径
//测试配置文件 安装路径下的/nginx/sbin/nginx -t 复制代码 //启动命令 安装路径下的/nginx/sbin/nginx //停止命令 安装路径下的/nginx/sbin/nginx -s stop 或者 : nginx -s quit //重启命令 安装路径下的/nginx/sbin/nginx -s reload 复制代码 //查看进程命令 ps -ef | grep nginx //平滑重启 kill -HUP Nginx主进程号
配置端口转发
配置config文件
server { listen 9100; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location ^~/api/datacheck/ { proxy_redirect off; proxy_set_header Host $host:9106; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 10m; client_body_buffer_size 256k; proxy_connect_timeout 60; proxy_send_timeout 60; proxy_read_timeout 60; proxy_buffer_size 4k; proxy_buffers 8 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; proxy_pass http://127.0.0.1::8080
在nginx中配置proxy_pass时,如果是按照^~匹配路径时,要注意proxy_pass后的url最后的/,当加上了/,相当于是绝对根路径,则nginx不会把location中匹配的路径部分代理走;如果没有/,则会把匹配的路径部分也给代理走。
location ^~ /static_js/
{
proxy_cache js_cache;
proxy_set_header Host js.test.com;
proxy_pass http://js.test.com/;
}
如上面的配置,如果请求的url是http://servername/static_js/test.html
会被代理成http://js.test.com/test.html
而如果这么配置
location ^~ /static_js/
{
proxy_cache js_cache;
proxy_set_header Host js.test.com;
proxy_pass http://js.test.com;
}
则会被代理到http://js.test.com/static_js/test.htm
当然,我们可以用如下的rewrite来实现/的功能
location ^~ /static_js/
{
proxy_cache js_cache;
proxy_set_header Host js.test.com;
rewrite /static_js/(.+)//1 break;
proxy_pass http://js.test.com;
}
参考地址:
非Centos下Nginx安装: https://www.cnblogs.com/taiyonghai/p/6728707.html