nginx地址重寫
1 問題
通過調整Nginx服務端配置,實現以下目標:
所有訪問a.html的請求,重定向到b.html;
所有訪問192.168.4.5的請求重定向至www.baidu.com;
所有訪問192.168.4.5/下面子頁面,重定向至www.baidu.com/下相同的頁面;
實現curl訪問不同的頁面。
2 方案
關於Nginx服務器的地址重寫,主要用到的配置參數是rewrite:
rewrite regex replacement flag
3 步驟
實現此案例需要按照如下步驟進行。
步驟一:修改配置文件(訪問a.html重定向到b.html)
1)修改Nginx服務配置:
[root@Proxy ~]# vim /usr/local/nginx/conf/nginx.conf
.. ..
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
rewrite /a.html /b.html; //註意看這裏
}
}
2)重新加載配置文件
[root@Proxy ~]# /usr/local/nginx/sbin/nginx -s reload
3)客戶端測試
[root@client ~]# firefox http://192.168.4.5/a.html
步驟二:修改配置文件(訪問192.168.4.5的請求重定向至www.baidu.con)
1) 修改Nginx服務配置
[root@Proxy ~]# vim /usr/local/nginx/conf/nginx.conf
.. ..
server {
listen 80;
server_name localhost;
rewrite ^/ http://www.baidu.com/; //註意看這裏
location / {
root html;
index index.html index.htm;
}
}
2)重新加載配置文件
[root@Proxy ~]# /usr/local/nginx/sbin/nginx -s reload
3)客戶端測試
[root@client ~]# firefox http://192.168.4.5
步驟三:修改配置文件(訪問192.168.4.5/下面子頁面,重定向至www.baidu.com/下相同的頁面)
1) 修改Nginx服務配置
[root@Proxy ~]# vim /usr/local/nginx/conf/nginx.conf
.. ..
server {
listen 80;
server_name localhost;
rewrite ^/(.*) http://www.baidu.com/$1; //註意看這裏
location / {
root html;
index index.html index.htm;
}
}
2)重新加載配置文件
[root@Proxy ~]# /usr/local/nginx/sbin/nginx -s reload
3)客戶端測試
[root@client ~]# firefox http://192.168.4.5
步驟三:修改配置文件(實現curl和火狐訪問相同連接返回的頁面不同)
1) 修改Nginx服務配置
.. ..
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
if ($http_user_agent ~* url) { //識別客戶端curl瀏覽器
rewrite ^(.*)$ /curl/$1 break; //註意看這裏
}
}
2)創建網頁目錄以及對應的頁面文件:
[root@Proxy ~]# echo "I am Normal page" > /usr/local/nginx/html/test.html
[root@Proxy ~]# mkdir -p /usr/local/nginx/html/curl/
[root@Proxy ~]# echo "I am is curl page" > /usr/local/nginx/html/curl/test.html
[root@Proxy ~]# cp /usr/share/backgrounds/gnome/Road.jpg \
> /usr/local/nginx/curl/test.jpg
2)重新加載配置文件
[root@Proxy ~]# /usr/local/nginx/sbin/nginx -s reload
4)客戶端測試
[root@client ~]# firefox http://192.168.4.5/test.html
[root@client ~]# curl http://192.168.4.5/test.html
[root@client ~]# curl http://192.168.4.5/test.jsp
nginx地址重寫