調整Nginx服務器配置,實現:
1.所有訪問a.html的請求,重定向到b.html;
2.所有訪問Nginx服務器(192.168.4.1)的請求重定向至www.baidu.com;
3.所有訪問Nginx服務器(192.168.4.1)/下面子頁面,重定向至www.baidu.com/下相同的頁面.
4.實現firefox與curl訪問相同頁面文件,返回不同的內容
總結地址重寫的格式有:
rewrite 舊地址 新地址 [選項];
last 不再讀其他rewrite
break 不再讀其他語句,結束請求
redirect 臨時重定向
permament 永久重定向
1. 所有訪問a.html的請求,重定向到b.html
[root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
......
server {
listen 80;
server_name localhost;
rewrite /a.html /b.html redirect; //地址跳轉到b.html
location / {
root html;
index index.html index.htm;
}
}
# echo "test page" > /usr/local/nginx/html/b.html //在網頁文件里寫入數據,用於測試
# /usr/local/nginx/sbin/nginx -s reload //重啟,加載配置
[root@client ~]# firefox http://192.168.4.5/a.html //客戶端測試,訪問a.html,但瀏覽器地址欄會自動跳轉到b.html的頁面
2.所有訪問Nginx服務器(192.168.4.1)的請求重定向至www.baidu.com
[root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
......
server {
listen 80;
server_name localhost;
rewrite ^/ http://baidu.com/ ; //地址跳轉到百度
location / {
root html;
index index.html index.htm;
}
}
# /usr/local/nginx/sbin/nginx -s reload //重啟,加載配置
[root@room9pc01 ~]# firefox http://192.168.4.1 //真機上訪問Nginx服務器,瀏覽器地址欄自動跳轉至www.baidu.com
3.所有訪問Nginx服務器(192.168.4.1)/下面子頁面,重定向至www.baidu.com/下相同的頁面
[root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
......
server {
listen 80;
server_name localhost;
rewrite ^/(.*)$ http://baidu.com/ $1; //地址跳轉到百度下的子頁面,這里用到了正則,即以/開頭,以任意內容結尾(.*)$
location / {
root html;
index index.html index.htm;
}
}
# /usr/local/nginx/sbin/nginx -s reload //重啟,加載配置
[root@room9pc01 ~]# firefox http://192.168.4.1/test //真機上訪問Nginx服務器下的子頁面,瀏覽器地址欄自動跳轉至www.baidu.com/子頁面
4.實現firefox與curl訪問相同頁面文件,返回不同的內容
4.1創建網頁目錄以及對應的頁面文件,用於測試:
# echo "I am normal page" > /usr/local/nginx/html/test.html
# mkdir -p /usr/local/nginx/html/firefox/
# echo "wo shi firefox page" > /usr/local/nginx/html/firefox/test.html
4.2修改Nginx服務配置
[root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
......
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
if ($http_user_agent ~* firefox) { //變量$http_user_agent能識別客戶端的firefox瀏覽器,這里的符號~示意正則匹配,符號*示意不區分大小寫
rewrite ^/(.*)$ /firefox/$1;
}
}
# /usr/local/nginx/sbin/nginx -s reload //重啟,加載配置
# firefox http://192.168.4.1/test.html //使用火狐瀏覽器訪問Nginx服務器
# curl http://192.168.4.1/test.html //本地curl訪問Nginx服務器
結束.
