1. 程式人生 > >nginx之地址重寫

nginx之地址重寫

nginx地址重寫

1,語法
格式:rewrite 舊地址 新地址 [選項]
選項:
rewrite 舊地址 新地址 [選項];
last 不再讀其他rewrite
break 不再讀其他語句,結束請求
redirect 臨時重定向
permament 永久重定向

2,實戰

1)實現訪問jluo.html重定向到jluocc.html(不跳轉位址列)
#vim /usr/local/nginx/conf/nginx.conf
ocation / {
root html;
index index.html index.htm;
rewrite /jluo.html /jluocc.html; #轉義
}

2)實現訪問jluo.html重定向到jluocc.html(跳轉位址列)
#vim /usr/local/nginx/conf/nginx.conf
ocation / {
root html;
index index.html index.htm;
rewrite /jluo.html /jluocc.html redirect; #轉義
}

3)實現訪問www.jluo.com的請求重定向到www.jluocc.cn去
server {
listen 80;
server_name www.jluo.com;
rewrite ^/ http://www.jluocc.cn/;
location / {
root html;
index index.html index.htm;
}
}

4)實現訪問www.jluo.com的子頁面,重定向到www.jluocc.cn相同的子頁面去
server {
listen 80;
server_name www.jluo.com;
rewrite ^/(.*) http://www.jluocc.cn/$1; //使用正則
location / {
root html;
index index.html index.htm;
}
}

5)實現不同的裝置訪問相同的地址返回的頁面不同
用途:實現部署不同頁面(手機端,電腦端)
如:實現curl和火狐訪問相同連結返回的頁面不同
[[email protected] ~]# echo "I am Normal page" > /usr/local/nginx/html/test.html
[[email protected] ~]# mkdir -p /usr/local/nginx/html/firefox/
[[email protected] ~]# echo "firefox page" > /usr/local/nginx/html/firefox/test.html
[[email protected]

~]# 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) { #識別客戶端firefox瀏覽器
rewrite ^(.*) /firefox/$1;
}
提示:
每個實驗做完都是需要重新載入配置檔案的,命令如下
[[email protected] ~]# /usr/local/nginx/sbin/nginx -s reload
#請先確保nginx是啟動狀態,否則執行該命令會報錯,報錯資訊如下:
#[error] open() "/usr/local/nginx/logs/nginx.pid" failed (2: No such file or directory)

3,nginx常量
#tail -1 /usr/local/nginx/log/access.log
192.168.4.254 -  tom  [31/Oct/2018:21:46:44 +0800] " GET / HTTP/1.1"  200 2 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"

$remote_addr:遠端客戶機的地址=> 192.168.4.254
$remote_user:遠端登入使用者,即為nginx使用者認證頁面登入的使用者=>tom 沒有即為 -
$time_local:訪問的時間=>31/Oct/2018:21:46:44 +0800
$request:請求方式=>GET / HTTP/1.1
$sttatus:請求返回的狀態碼=>200
$body_bytes_sent:位元組大小=>2
$http_user_agent:客戶端裝置資訊=>"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"