nginx+php 使用的時候經常需要偽靜態,一般大家都手動設置。那有沒有辦法讓 nginx 自動補全路徑呢?
這兩天折騰很久,才實現了這樣一個功能:
請求 /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.
雖然這種損耗性能的行為不適合部署,但在本機調試的時候還是能夠帶來方便的 :)
server 端應有如下代碼,其他部分使用自己的配置:
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 - 基本上都用這個Flag。
break - 中止Rewirte,不在繼續匹配
redirect - 返回臨時重定向的HTTP狀態302
permanent - 返回永久重定向的HTTP狀態301
規則:
一般在非根的location中配置rewrite,都是用的break;而根的location使用last比較好,因為如果配置了fastcgi或代理訪問jsp文件的話,在根location下用break是訪問不到
正則表達式形式的模式匹配,如~*和~
新聞熱點
疑難解答