首页 > 服务器维护 > nginx

Nginx的伪静态配置中使用rewrite来实现自动补全的实例

发布时间:2016-1-27 20:13

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是访问不到

正则表达式形式的模式匹配,如~*和~

标签:[!--infotagslink--]

您可能感兴趣的文章: