最近手上有两台服务器,都是cenos7系统,不同的是,一个是LAMP环境,一个是LNMP环境。对于Nginx,之前了解的时候,就知道nginx在反向代理和负载均衡方面的能力比较强,于是今天就拿nginx服务器来尝试了一下配置反向代理,结果发现流程相当的简单,下面就是今天的笔记。
项目目的:对指向nginx服务器域名做两个反向代理,域名的一级目录(http://域名)指向本机,域名的二级目录(http://域名/service)指向另外一台服务器。
项目过程中出现的问题: 在安装ngnix后,在.conf文件夹中有一个默认的配置文件defaulut.conf,该文件的一个功能是设置监听localhost的80端口,然后我在新增的配置中,也将一级目录(http://域名:80)指向localhost的80端口, 这样子将造成nginx运行出错,解决方法是,将default.conf中的80端口配置成8080,然后在新的配置文件,将一级目录(http://域名:80)指向localhost的8080端口,结果完美解决问题。
项目配置文件展示:
#default.conf
server {
listen 8080;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/log/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
#second.conf
upstream lgrService{
server XXX.XXX.XX.XX:80 weight=1; #另外一台服务器
}
upstream local{
server localhost:8080 weight=1; #本地服务器
}
server {
#侦听的80端口
listen 80;
server_name www.XXX.com;
#设定查看Nginx状态的地址
location /nginxstatus{
stub_status on;
access_log on;
auth_basic "nginxstatus";
auth_basic_user_file htpasswd;
}
location /service/ {
#DemoBackend1后面的斜杠是一个关键,没有斜杠的话就会传递service到后端节点导致404
proxy_pass http://lgrService/;
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;
}
location / {
#DemoBackend1后面的斜杠是一个关键,没有斜杠的话就会传递service到后端节点导致404
proxy_pass http://local/;
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;
}
}
结果:
(1)输入http://域名 访问nginx服务器的项目
(2)输入http://域名/service 访问另外一台服务器