Nginx location匹配順序如下: ~ 開頭表示區分大小寫的正則匹配; ~* 開頭表示不區分大小寫的正則匹配 整體匹配優先順序 =精確匹配 > ^~首碼匹配 > 正則匹配 > 普通首碼字元串匹配 rewrite塊可直接放在server段內,也可置於location段內。請求到達nginx後,U ...
Nginx location匹配順序如下:
- 用首碼字元串定義的location規則對URI進行匹配測試。
- =號定義了精確的首碼字元串匹配,如果發現精確匹配則使用當前規則。否則繼續下一步匹配。
- 匹配其它普通字元串,並存儲最長匹配。如果匹配以^~開始的規則,則使用當前匹配,否則繼續下一步匹配。
- 按順序對URI進行正則規則匹配,發現匹配後停止並使用當前匹配。若所有正則都不匹配,則使用第3步存儲的最長匹配規則。
- ~ 開頭表示區分大小寫的正則匹配;
- ~* 開頭表示不區分大小寫的正則匹配
整體匹配優先順序 =精確匹配 > ^~首碼匹配 > 正則匹配 > 普通首碼字元串匹配
rewrite塊可直接放在server段內,也可置於location段內。請求到達nginx後,URI會進行如下處理:
URI->server rewrite->new URI->location匹配
在location規則匹配過程中若對url進行了重寫,則要重新開始規則匹配。若迴圈10次後仍沒有找到真實存在的文件,伺服器會返回500錯誤。
rewrite指令可以附帶一個標誌位 last/break;對此,我的理解是兩者都會終止rewrite的執行,last一般用在server段,break一般用在location內。last執行完還要進行location匹配,而break則不再進行location匹配。
基於CI框架的nginx配置(windows環境):
#user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; #開啟rewrite日誌 測試用 rewrite日誌寫在error_log里 rewrite_log on; error_log logs/error.log notice; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #tcp_nodelay on; fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; fastcgi_buffer_size 128k; fastcgi_buffers 4 128k; fastcgi_busy_buffers_size 256k; fastcgi_temp_file_write_size 256k; #gzip on; gzip on; gzip_min_length 1k; gzip_buffers 4 32k; gzip_http_version 1.1; gzip_comp_level 2; gzip_types text/plain application/x-javascript text/css application/xml; gzip_vary on; gzip_disable "MSIE [1-6]."; server_names_hash_bucket_size 128; client_max_body_size 100m; client_header_buffer_size 256k; large_client_header_buffers 4 256k; server { listen 80; server_name citest.com; index index.html index.php; root "d:/www/ci"; access_log logs/ciaccess.log main; if (!-e $request_filename) { rewrite ^/(.*)$ /index.php/$1 last; } location ~ \.php(.*)$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; include fastcgi_params; } location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 12h; } } #include vhosts.conf; }