当前位置 主页 > 服务器问题 > nginx问题汇总 >

    详解Nginx 反向代理、负载均衡、页面缓存、URL重写及读写分离详(15)

    栏目:nginx问题汇总 时间:2018-11-21 16:18

    2.简单案例

    注,由于配置文件内容较多,为了让大家看着方便,我们备份一下配置文件,打开一个新的配置文件。

    [root@nginx ~]# cd /etc/nginx/[root@nginx nginx]# mv nginx.conf nginx.conf.proxy[root@nginx nginx]# cp nginx.conf.bak nginx.conf[root@nginx nginx]# vim /etc/nginx/nginx.confserver {   listen    80;   server_name localhost;   #charset koi8-r;   #access_log logs/host.access.log main;   location / {     root  html;     index index.html index.htm;     rewrite ^/bbs/(.*)$ http://192.168.18.201/forum/$1;   }}

    准备forum目录与测试文件

    [root@web1 ~]# cd /var/www/html/[root@web1 html]# lsindex.html[root@web1 html]# mkdir forum[root@web1 html]# cd forum/[root@web1 forum]# vim index.html<h1>forum page!</h1>

    测试一下

    t13

    好了,下面我们来测试一下rewrite重写。

    3.重新加载一下配置文件

    [root@nginx 63]# service nginx reloadnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful重新载入 nginx:                      [确定]

    4.测试一下

    t14

    注,大家可以从图中看出,status code 302指的是临时重定向,那就说明我们rewrite重写配置成功。大家知道302是临时重定向而301是永久重定向,那么怎么实现永久重定向呢。一般服务器与服务器之间是临时重定向,服务器内部是永久重定向。下面我们来演示一下永久重定向。

    5.配置永久重定向

    [root@nginx nginx]# vim /etc/nginx/nginx.confserver {    listen    80;    server_name localhost;    #charset koi8-r;    #access_log logs/host.access.log main;    location / {      root  html;      index index.html index.htm;      rewrite ^/bbs/(.*)$ /forum/$1;    }}

    准备forum目录与测试文件

    [root@nginx ~]# cd /usr/html/[root@nginx html]# ls50x.html index.html[root@nginx html]# mkdir forum[root@nginx html]# cd forum/[root@nginx forum]# vim index.html<h1>192.168.18.208 forum page</h1>

    6.重新加载一下配置文件

    [root@nginx ~]# service nginx reloadnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful重新载入 nginx:                      [确定]

    7.测试一下

    t16

    注,大家从图中可以看到,我们访问bbs/是直接帮我们跳转到forum/下,这种本机的跳转就是永久重定向也叫隐式重定向。好了,rewrite重定向我们就说到这里了,想要查询更多关于重定向的指令请参考官方文档。最后,我们来说一下读写分离。

    八、Nginx之读写分离

    1.实验拓扑

    nginx3

    需求分析,前端一台nginx做负载均衡反向代理,后面两台httpd服务器。整个架构是提供BBS(论坛)服务,有一需求得实现读写分离,就是上传附件的功能,我们上传的附件只能上传到Web1,然后在Web1上利用rsync+inotify实现附件同步,大家都知道rsync+inotify只能是主向从同步,不能双向同步。所以Web1可进行写操作,而Web2只能进行读操作,这就带来读写分离的需求,下面我们就来说一下,读写分离怎么实现。