Nginx中rewrite實現二級域名、三級域名、泛域名、路徑的重寫

最多見的: 靜態地址重定向到帶參數的動態地址php

rewrite "^(.*)/service/(.*)\.html$" $1/service.php?sid=$2 permanent;  html

反過來: 帶參數的動態地址重定向到靜態地址nginx

if ($query_string ~* id=(.*)) { 
set $id $1; 
rewrite "^(.*)/article.asp$" $1/article/$id.htm last; 



泛域名解析 

view plaincopy to clipboardprint?
server_name www.w3cgroup.com *.w3cgroup.com; 
server_name_in_redirect off; 
#設置默認root 
set $rootdir /usr/local/nginx/html/w3cgroup/;正則表達式

#匹配三級或三級以上的域名cookie

if ($host ~* ^(.+)\.([^\.]+)\.([^\.]+)\.([^\.]+)$)  {orm

}
#匹配三級域名 
if ($host ~* ^([^\.]+)\.([^\.]+)\.([^\.]+)\.([^\.]+)$) { 
#三級域名中有訪問指定的目錄則重定向到相應的二級域名下 
rewrite "^.+upload/?(.*)$" http://upload.w3cgroup.com/$1 permanent; 
rewrite "^.+ijc/?(.*)$" http://ijc.w3cgroup.com/$1 permanent; 
break; 

#匹配二級域名 
if ($host ~* ^([^\.]+)\.([^\.]+)\.([^\.]+)$) { 
set $rs1 $1; 

#設置www時root 
if ($rs1 ~* ^www$) { 
set $rootdir /usr/local/nginx/html/platform_ig/; 
#二級域名中有訪問指定的目錄則重定向到相應的二級域名下,注意,這裏要使用last 
rewrite "^.+upload/?(.*)$" upload/$1 last; 
rewrite "^.+ijc/?(.*)$" ijc/$1 last; 
break; 

#設置非www二級域名時root 
if ($rs1 !~* ^www$) { 
set $rootdir /usr/local/nginx/html/w3cgroup/$rs1; 
#二級域名中有訪問指定的目錄則重定向到相應的二級域名下 
rewrite "^.+upload/?(.*)$" http://upload.w3cgroup.com/$1 permanent; 
rewrite "^.+ijc/?(.*)$" http://ijc.w3cgroup.com/$1 permanent; 
break; 

#應用root 
root $rootdir; 
index index.php index.html; 
error_page 404 http://$host/; 

注意:if () {} 之間須要空格,不然Nginx.conf會報unknow directive 錯誤! 

參考: 

Nginx Rewrite Flags 
* last 至關於Apache裏的[L]標記,表示完成rewrite
* break 終止匹配, 再也不匹配後面的規則
* redirect 返回302臨時重定向
* permanent 返回301永久重定向

Nginx正則表達式匹配 
* ~ 爲區分大小寫匹配
* ~* 爲不區分大小寫匹配
* !~和!~*分別爲區分大小寫不匹配及不區分大小寫不匹配

Nginx文件及目錄匹配 
* -f和!-f用來判斷是否存在文件
* -d和!-d用來判斷是否存在目錄
* -e和!-e用來判斷是否存在文件或目錄
* -x和!-x用來判斷文件是否可執行

Nginx全局變量 
view plaincopy to clipboardprint?
$args 
$content_length 
$content_type 
$document_root 
$document_uri 
$host 
$http_user_agent 
$http_cookie 
$limit_rate 
$request_body_file 
$request_method 
$remote_addr 
$remote_port 
$remote_user 
$request_filename 
$request_uri 
$query_string 
$scheme 
$server_protocol 
$server_addr 
$server_name 
$server_port 
$uri server

相關文章
相關標籤/搜索