nginx+php 使用的時(shí)候經(jīng)常需要偽靜態(tài),一般大家都手動(dòng)設(shè)置。那有沒有辦法讓 nginx 自動(dòng)補(bǔ)全路徑呢?
這兩天折騰很久,才實(shí)現(xiàn)了這樣一個(gè)功能:
請(qǐng)求 /a/b/c
若文件不存在,查找 /a/b/index.php,/c 作為 PATH_INFO;
若文件不存在,查找 /a/index.php,/b/c 作為 PATH_INFO;
若文件不存在,查找 /index.php,/a/b/c 作為 PATH_INFO;
若文件不存在,返回 404.
雖然這種損耗性能的行為不適合部署,但在本機(jī)調(diào)試的時(shí)候還是能夠帶來方便的 :)
server 端應(yīng)有如下代碼,其他部分使用自己的配置:
index index.php index.html index.htm;location / { set $path $request_uri; set $path_info ""; try_files $uri $uri/ @404;}location @404 { if ($path ~ ^(.*)(/.+)$) { set $path $1/index.php; set $path_info $2; rewrite .* $path last; } return 404;}location ~ .+.php($|/) { fastcgi_split_path_info ^(.+.php)(/.+)$; if ($path_info !~ .*) { set $path_info $fastcgi_path_info; } try_files $fastcgi_script_name @404php; fastcgi_param PATH_INFO $path_info; fastcgi_index index.php; include fastcgi.conf; fastcgi_pass unix:/usr/local/var/run/php-fpm.sock; fastcgi_connect_timeout 60; fastcgi_send_timeout 300; fastcgi_read_timeout 300;}location @404php { if ($path = /index.php) { return 404; } if ($path ~ ^(.*)(/.+)/index.php$) { set $path_info $2; set $path $1/index.php; rewrite .* $path last; } return 404;}Rewrite的Flags
last - 基本上都用這個(gè)Flag。
break - 中止Rewirte,不在繼續(xù)匹配
redirect - 返回臨時(shí)重定向的HTTP狀態(tài)302
permanent - 返回永久重定向的HTTP狀態(tài)301
規(guī)則:
一般在非根的location中配置rewrite,都是用的break;而根的location使用last比較好,因?yàn)槿绻渲昧薴astcgi或代理訪問jsp文件的話,在根location下用break是訪問不到
正則表達(dá)式形式的模式匹配,如~*和~
新聞熱點(diǎn)
疑難解答
圖片精選