在url優化過程中,不可避免的涉及到nginx rewrite規則。那么nginx rewrite是如何配置的呢?
rewrite可以出現的地方有4個:NGX_HTTP_SRV_CONF,NGX_HTTP_SIF_CONF,NGX_HTTP_LOC_CONF,NGX_HTTP_LIF_CONF。分別對應著:
NGX_HTTP_SRV_CONF:配置文件中的server域中的任何地方;NGX_HTTP_SIF_CONF:配置文件中server域中的if配置中;NGX_HTTP_LOC_CONF:配置文件中的location域中的任何地方;NGX_HTTP_LIF_CONF:配置文件中的location域中的if配置中;
舉例如下:
//...server { //... rewrite "^/+$" /index.php break; if ($uri ~* "^/+abc") { rewrite "^/+abc" /abc/index.php break; } location /xy { rewrite "^/+xy$" /xy/index.php break; }}?1其中location的詳細描述和location的強大功能可以在本網站搜索框中輸入“ngingx location”來搜索。
補充
1.break指令
默認值:none ;使用環境:server,location,if ;
該指令的作用是完成當前的規則集,不再處理rewrite指令。
2.if指令
默認值:none ;使用環境:server,location
該指令用于檢查一個條件是否符合,如果條件符合,則執行大括號內的語句。If指令不支持嵌套,不支持多個條件&&和||處理。
A.變量名,錯誤的值包括:空字符串""或者任何以0開始的字符串B.變量比較可以使用"="(表示等于)和"!="(表示不等于)C.正則表達式模式匹配可以使用"~*"和"~"符號D."~"符號表示區分大小寫字母的匹配E."~*"符號表示不區分大小寫字母的匹配F."!~"和"!~*"符號的作用剛好和"~"、"~*"相反,表示不匹配G."-f"和"!-f"用來判斷文件是否存在H."-d"和"!-d"用來判斷目錄是否存在I."-e"和"!-e"用來判斷文件或目錄是否存在J."-x"和"!-x"用來判斷文件是否為可執行K.部分正則表達式可以在()內,用$1~$9來訪問3.return指令
語法:return code ;使用環境:server,location,if ;
該指令用于結束規則的執行并返回狀態碼給客戶端。
示例:如果訪問的URL以".sh"或".bash"結尾,則返回403狀態碼
location ~ .*.(sh|bash)?${return 403;}4.rewrite 指令
語法:rewrite regex replacement flag
默認值:none ; 使用環境:server,location,if
該指令根據表達式來重定向URI,或者修改字符串。指令根據配置文件中的順序來執行。注意重寫表達式只對相對路徑有效。如果你想配對主機名,你應該使用if語句,示例如下:
if( $host ~* www.(.*) ){set $host_without_www $1;rewrite ^(.*)$ http://$host_without_www$1 permanent;}
rewrite指令的最后一項參數為flag標記,支持flag標記有:
1.last 相當于apache里面的[L]標記,表示rewrite。
2.break本條規則匹配完成后,終止匹配,不再匹配后面的規則。
3.redirect 返回302臨時重定向,瀏覽器地址會顯示跳轉后的URL地址。
4.permanent 返回301永久重定向, 瀏覽器地址會顯示跳轉后的URL地址。
使用last和break實現URI重寫,瀏覽器地址欄不變。而且兩者有細微差別,使用alias指令必須用last標記;使用proxy_pass指令時,需要使用break標記。Last標記在本條rewrite規則執行完畢后,會對其所在server{......}標簽重新發起請求,而break標記則在本條規則匹配完成后,終止匹配。
一般在跟location中(location /{...})或直接在server標簽中編寫rewrite規則,推薦使用last標記;在非根location中(location /cms/{...}),則使用break。
如果URI中含有參數(/app/test.php?id=5),默認情況下參數會被自動附加到替換串上,你可以通過在替換串的末尾加上?標記來解決這一問題。
例如:
rewrite ^/test(.*)$ http://www.111cn.net/home permanent;訪問http://www.111cn.net/test?id=5 會跳轉到 http://www.111cn.net/home?id=5
例如:如果我們將類似URL /photo/123456 重定向到 /path/to/photo/12/1234/123456.png
Rewrite "/photo/([0-9]{2})([0-9]{2})([0-9]{2})" /path/to/photo/$1/$1$2/$1$2$3.png ;
注:如果正則表達式里面有花括號"{"或"}" ,應該使用雙引號或單引號。
5.Set指令
語法:set variable value ; 默認值:none ; 使用環境:server,location,if;
該指令用于定義一個變量,并給變量賦值。變量的值可以為文本、變量以及文本變量的聯合。
示例:set $varname "hello world";
6.Uninitialized_variable_warn指令
語法:uninitialized_variable_warn on|off
使用環境:http,server,location,if
該指令用于開啟和關閉未初始化變量的警告信息,默認值為開啟。
7.Nginx Rewrite可以用到的全局變量
$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
====(詳情見附錄)====
Nginx的Rewrite規則編寫實例
1.當訪問的文件和目錄不存在時,重定向到某個php文件
if( !-e $request_filename ){rewrite ^/(.*)$ index.php last;}
2.目錄對換 /123456/xxxx ====> /xxxx?id=123456
rewrite ^/(d+)/(.+)/ /$2?id=$1 last;
3.如果客戶端使用的是IE瀏覽器,則重定向到/ie目錄下
if( $http_user_agent ~ MSIE){rewrite ^(.*)$ /ie/$1 break;}
4.禁止訪問多個目錄
location ~ ^/(cron|templates)/{deny all;break;}
5.禁止訪問以/data開頭的文件
location ~ ^/data{deny all;}
6.禁止訪問以.sh,.flv,.mp3為文件后綴名的文件
location ~ .*.(sh|flv|mp3)${return 403;}
7.設置某些類型文件的瀏覽器緩存時間
location ~ .*.(gif|jpg|jpeg|png|bmp|swf)${expires 30d;}location ~ .*.(js|css)${expires 1h;}8.給favicon.ico和robots.txt設置過期時間;這里為favicon.ico為99天,robots.txt為7天并不記錄404錯誤日志
location ~(favicon.ico) { log_not_found off; expires 99d; break; } location ~(robots.txt) { log_not_found off; expires 7d; break; }
9.設定某個文件的過期時間;這里為600秒,并不記錄訪問日志
location ^~ /html/scripts/loadhead_1.js { access_log off; root /opt/lampp/htdocs/web; expires 600; break; }
10.文件反盜鏈并設置過期時間這里的return 412 為自定義的http狀態碼,默認為403,方便找出正確的盜鏈的請求“rewrite ^/ http://img.111cn.net/leech.gif;”顯示一張防盜鏈圖片“access_log off;”不記錄訪問日志,減輕壓力“expires 3d”所有文件3天的瀏覽器緩存
location ~* ^.+.(jpg|jpeg|gif|png|swf|rar|zip|css|js)$ { valid_referers none blocked *.c1gstudio.com *.c1gstudio.net localhost 208.97.167.194; if ($invalid_referer) { rewrite ^/ http://img.111cn.net/leech.gif; return 412; break; } access_log off; root /opt/lampp/htdocs/web; expires 3d; break; }
11.只充許固定ip訪問網站,并加上密碼
root /opt/htdocs/www; allow 208.97.167.194; allow 222.33.1.2; allow 231.152.49.4; deny all; auth_basic “C1G_ADMIN”; auth_basic_user_file htpasswd;
12將多級目錄下的文件轉成一個文件,增強seo效果/job-123-456-789.html 指向/job/123/456/789.html
rewrite ^/job-([0-9]+)-([0-9]+)-([0-9]+).html$ /job/$1/$2/jobshow_$3.html last;
13.將根目錄下某個文件夾指向2級目錄如/shanghaijob/ 指向 /area/shanghai/如果你將last改成permanent,那么瀏覽器地址欄顯是/location/shanghai/
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;
上面例子有個問題是訪問/shanghai 時將不會匹配
rewrite ^/([0-9a-z]+)job$ /area/$1/ last; rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;
這樣/shanghai 也可以訪問了,但頁面中的相對鏈接無法使用,如./list_1.html真實地址是/area/shanghia/list_1.html會變成/list_1.html,導至無法訪問。
那我加上自動跳轉也是不行咯(-d $request_filename)它有個條件是必需為真實目錄,而我的rewrite不是的,所以沒有效果
if (-d $request_filename){ rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent; }
知道原因后就好辦了,讓我手動跳轉吧
rewrite ^/([0-9a-z]+)job$ /$1job/ permanent; rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;
14.文件和目錄不存在的時候重定向:
if (!-e $request_filename) { proxy_pass http://127.0.0.1; }
Nginx和Apache的Rewrite規則實例對比
1.一般簡單的Nginx和Apache規則的區別不大,基本能夠完全兼容,例如:
Apache: RewriteRule ^/abc/$ /web/abc.php [L]
Nginx: rewrite ^/abc/$ /web/abc.php last ;
我們可以看出來只要把Apache的RewriteRule改為Nginx的rewrite,Apache的[L]改為last 即可。
如果將Apache的規則改為Nginx規則后,用命令Nginx -t 檢查發現錯誤,則我們可以嘗試給條件加上引號,例如:
rewrite “^/([0-9]{5}).html$” /x.php?id=$1 last;
2.Apache和Nginx的Rewrite規則在URL跳轉時有細微區別:
Apache: RewriteRule ^/html/([a-zA-Z]+)/.*$ /$1/ [R=301,L]
Nginx: rewrite ^/html/([a-zA-Z]+)/.*$ http://$host/$1/ premanent ;
我們可以看到在Nginx的跳轉中,我們需要加上http://$host,這是在Nginx中強烈要求的。
3.下面是一些Apache和Nginx規則的對應關系
a.Apache的RewriteCond對應Nginx的if
b.Apache的RewriteRule對應Nginx的rewrite
c.Apache的[R]對應Nginx的redirect
d.Apache的[P]對應Nginx的last
e.Apache的[R,L]對應Nginx的redirect
f.Apache的[P,L]對應Nginx的last
g.Apache的[PT,L]對應Nginx的last
例如:允許指定的域名訪問本站,其他的域名一律轉向www.111cn.net
Apache:
RewriteCond %{HTTP_HOST} !^(.*?).aaa.com$ [NC]RewriteCond %{HTTP_HOST} !^localhost$ RewriteCond %{HTTP_HOST} !^192.168.0.(.*?)$RewriteRule ^/(.*)$ http://www.111cn.net [R,L]
Nginx:
if( $host ~* ^(.*).aaa.com$ ){set $allowHost ‘1’;}if( $host ~* ^localhost ){set $allowHost ‘1’;}if( $host ~* ^192.168.1.(.*?)$ ){set $allowHost ‘1’;}if( $allowHost !~ ‘1’ ){rewrite ^/(.*)$ http://www.111cn.net redirect ;}《附錄:nginx全局變量》
經常需要配置Nginx ,其中有許多以 $ 開頭的變量,經常需要查閱nginx 所支持的變量。Nginx支持的http變量實現在 ngx_http_variables.c 的 ngx_http_core_variables存儲實現
ngx_http_core_variables static ngx_http_variable_t ngx_http_core_variables[] = { { ngx_string("http_host"), NULL, ngx_http_variable_header, offsetof(ngx_http_request_t, headers_in.host), 0, 0 }, { ngx_string("http_user_agent"), NULL, ngx_http_variable_header, offsetof(ngx_http_request_t, headers_in.user_agent), 0, 0 }, { ngx_string("http_referer"), NULL, ngx_http_variable_header, offsetof(ngx_http_request_t, headers_in.referer), 0, 0 }, #if (NGX_HTTP_GZIP) { ngx_string("http_via"), NULL, ngx_http_variable_header, offsetof(ngx_http_request_t, headers_in.via), 0, 0 }, #endif #if (NGX_HTTP_PROXY || NGX_HTTP_REALIP) { ngx_string("http_x_forwarded_for"), NULL, ngx_http_variable_header, offsetof(ngx_http_request_t, headers_in.x_forwarded_for), 0, 0 }, #endif { ngx_string("http_cookie"), NULL, ngx_http_variable_headers, offsetof(ngx_http_request_t, headers_in.cookies), 0, 0 }, { ngx_string("content_length"), NULL, ngx_http_variable_header, offsetof(ngx_http_request_t, headers_in.content_length), 0, 0 }, { ngx_string("content_type"), NULL, ngx_http_variable_header, offsetof(ngx_http_request_t, headers_in.content_type), 0, 0 }, { ngx_string("host"), NULL, ngx_http_variable_host, 0, 0, 0 }, { ngx_string("binary_remote_addr"), NULL, ngx_http_variable_binary_remote_addr, 0, 0, 0 }, { ngx_string("remote_addr"), NULL, ngx_http_variable_remote_addr, 0, 0, 0 }, { ngx_string("remote_port"), NULL, ngx_http_variable_remote_port, 0, 0, 0 }, { ngx_string("server_addr"), NULL, ngx_http_variable_server_addr, 0, 0, 0 }, { ngx_string("server_port"), NULL, ngx_http_variable_server_port, 0, 0, 0 }, { ngx_string("server_protocol"), NULL, ngx_http_variable_request, offsetof(ngx_http_request_t, http_protocol), 0, 0 }, { ngx_string("scheme"), NULL, ngx_http_variable_scheme, 0, 0, 0 }, { ngx_string("request_uri"), NULL, ngx_http_variable_request, offsetof(ngx_http_request_t, unparsed_uri), 0, 0 }, { ngx_string("uri"), NULL, ngx_http_variable_request, offsetof(ngx_http_request_t, uri), NGX_HTTP_VAR_NOCACHEABLE, 0 }, { ngx_string("document_uri"), NULL, ngx_http_variable_request, offsetof(ngx_http_request_t, uri), NGX_HTTP_VAR_NOCACHEABLE, 0 }, { ngx_string("request"), NULL, ngx_http_variable_request_line, 0, 0, 0 }, { ngx_string("document_root"), NULL, ngx_http_variable_document_root, 0, NGX_HTTP_VAR_NOCACHEABLE, 0 }, { ngx_string("realpath_root"), NULL, ngx_http_variable_realpath_root, 0, NGX_HTTP_VAR_NOCACHEABLE, 0 }, { ngx_string("query_string"), NULL, ngx_http_variable_request, offsetof(ngx_http_request_t, args), NGX_HTTP_VAR_NOCACHEABLE, 0 }, { ngx_string("args"), ngx_http_variable_request_set, ngx_http_variable_request, offsetof(ngx_http_request_t, args), NGX_HTTP_VAR_CHANGEABLE|NGX_HTTP_VAR_NOCACHEABLE, 0 }, { ngx_string("is_args"), NULL, ngx_http_variable_is_args, 0, NGX_HTTP_VAR_NOCACHEABLE, 0 }, { ngx_string("request_filename"), NULL, ngx_http_variable_request_filename, 0, NGX_HTTP_VAR_NOCACHEABLE, 0 }, { ngx_string("server_name"), NULL, ngx_http_variable_server_name, 0, 0, 0 }, { ngx_string("request_method"), NULL, ngx_http_variable_request_method, 0, NGX_HTTP_VAR_NOCACHEABLE, 0 }, { ngx_string("remote_user"), NULL, ngx_http_variable_remote_user, 0, 0, 0 }, { ngx_string("body_bytes_sent"), NULL, ngx_http_variable_body_bytes_sent, 0, 0, 0 }, { ngx_string("request_completion"), NULL, ngx_http_variable_request_completion, 0, 0, 0 }, { ngx_string("request_body"), NULL, ngx_http_variable_request_body, 0, 0, 0 }, { ngx_string("request_body_file"), NULL, ngx_http_variable_request_body_file, 0, 0, 0 }, { ngx_string("sent_http_content_type"), NULL, ngx_http_variable_sent_content_type, 0, 0, 0 }, { ngx_string("sent_http_content_length"), NULL, ngx_http_variable_sent_content_length, 0, 0, 0 }, { ngx_string("sent_http_location"), NULL, ngx_http_variable_sent_location, 0, 0, 0 }, { ngx_string("sent_http_last_modified"), NULL, ngx_http_variable_sent_last_modified, 0, 0, 0 }, { ngx_string("sent_http_connection"), NULL, ngx_http_variable_sent_connection, 0, 0, 0 }, { ngx_string("sent_http_keep_alive"), NULL, ngx_http_variable_sent_keep_alive, 0, 0, 0 }, { ngx_string("sent_http_transfer_encoding"), NULL, ngx_http_variable_sent_transfer_encoding, 0, 0, 0 }, { ngx_string("sent_http_cache_control"), NULL, ngx_http_variable_headers, offsetof(ngx_http_request_t, headers_out.cache_control), 0, 0 }, { ngx_string("limit_rate"), ngx_http_variable_request_set_size, ngx_http_variable_request_get_size, offsetof(ngx_http_request_t, limit_rate), NGX_HTTP_VAR_CHANGEABLE|NGX_HTTP_VAR_NOCACHEABLE, 0 }, { ngx_string("nginx_version"), NULL, ngx_http_variable_nginx_version, 0, 0, 0 }, { ngx_string("hostname"), NULL, ngx_http_variable_hostname, 0, 0, 0 }, { ngx_string("pid"), NULL, ngx_http_variable_pid, 0, 0, 0 }, { ngx_null_string, NULL, NULL, 0, 0, 0 } };把這些變量提取下,總結如下:
arg_PARAMETER #這個變量包含GET請求中,如果有變量PARAMETER時的值。args #這個變量等于請求行中(GET請求)的參數,例如foo=123&bar=blahblah;binary_remote_addr #二進制的客戶地址。body_bytes_sent #響應時送出的body字節數數量。即使連接中斷,這個數據也是精確的。content_length #請求頭中的Content-length字段。content_type #請求頭中的Content-Type字段。cookie_COOKIE #cookie COOKIE變量的值document_root #當前請求在root指令中指定的值。document_uri #與uri相同。host #請求主機頭字段,否則為服務器名稱。hostname #Set to the machine’s hostname as returned by gethostnamehttp_HEADERis_args #如果有args參數,這個變量等于”?”,否則等于”",空值。http_user_agent #客戶端agent信息http_cookie #客戶端cookie信息limit_rate #這個變量可以限制連接速率。query_string #與args相同。request_body_file #客戶端請求主體信息的臨時文件名。request_method #客戶端請求的動作,通常為GET或POST。remote_addr #客戶端的IP地址。remote_port #客戶端的端口。remote_user #已經經過Auth Basic Module驗證的用戶名。request_completion #如果請求結束,設置為OK. 當請求未結束或如果該請求不是請求鏈串的最后一個時,為空(Empty)。request_method #GET或POSTrequest_filename #當前請求的文件路徑,由root或alias指令與URI請求生成。request_uri #包含請求參數的原始URI,不包含主機名,如:”/foo/bar.php?arg=baz”。不能修改。scheme #HTTP方法(如http,https)。server_protocol #請求使用的協議,通常是HTTP/1.0或HTTP/1.1。server_addr #服務器地址,在完成一次系統調用后可以確定這個值。server_name #服務器名稱。server_port #請求到達服務器的端口號。
新聞熱點
疑難解答