# nginx的try_files

nginx的try_files

http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

try_files

- 说明
语法 try_files file ... uri; try_files file ... =code;
默认 ——
上下文 server、location

以指定顺序检查文件是否存在,并使用第一个找到的文件进行请求处理。处理将在当前上下文中执行。指向文件的路径根据 rootalias 指令从 file 参数构造。可以通过在名称末尾指定斜线来检查目录是否存在,例如,$URI/。如果找不到任何文件,则内部重定向将指向最后一个参数中指定的 uri。例如:

location /images/ {
    try_files $uri /images/default.gif;
}

location = /images/default.gif {
    expires 30s;
}

最后一个参数也可以指向一个命名的 location ,如以下示例。从 0.7.51 版本开始,最后一个参数也可以是一个 code

location / {
    try_files $uri $uri/index.html $uri.html =404;
}

代理 Mongrel 示例:

location / {
    try_files /system/maintenance.html
              $uri $uri/index.html $uri.html
              @mongrel;
}

location @mongrel {
    proxy_pass http://mongrel;
}

Drupal/FastCGI 示例:

location / {
    try_files $uri $uri/ @drupal;
}

location ~ \.php$ {
    try_files $uri @drupal;

    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;
    fastcgi_param SCRIPT_NAME     $fastcgi_script_name;
    fastcgi_param QUERY_STRING    $args;

    ... other fastcgi_param's
}

location @drupal {
    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to/index.php;
    fastcgi_param SCRIPT_NAME     /index.php;
    fastcgi_param QUERY_STRING    q=$uri&$args;

    ... other fastcgi_param's
}

在以下示例中

location / {
    try_files $uri $uri/ @drupal;
}

try_files 指令相当于

location / {
    error_page 404 = @drupal;
    log_not_found off;
}

还有一个示例

location ~ \.php$ {
    try_files $uri @drupal;

    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;

    ...
}

在将请求传递给 FastCGI 服务器之前,try_files 将检查 PHP 文件是否存在。

Wordpress 与 Joomla 示例:

location / {
    try_files $uri $uri/ @wordpress;
}

location ~ \.php$ {
    try_files $uri @wordpress;

    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;
    ... other fastcgi_param's
}

location @wordpress {
    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to/index.php;
    ... other fastcgi_param's
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章