2

每当我在 url nginx return 中放置一个已知的文件扩展名时404 Not Found

domain.com/myroute.fooanddomain.com/foo/myroute.foo很好,但是domain.com/myroute.phpand domain.com/foo/myroute.php(或例如 .css、.js)返回404 Not Found.

我的 nginx 服务器配置:

server {
        listen          80;
        server_name     domain.com;
        root            /var/www/path/public;

        charset utf-8;
        gzip on;

        #access_log  logs/host.access.log  main;

        location / {
                index index.html index.php index.htm;
                try_files $uri $uri/ /index.php?q=$uri&$args;
        }

        location ~ \.php$ {
                try_files                       $uri = 404;
                fastcgi_pass    unix:/var/run/php5-fpm.sock;
                fastcgi_index   index.php;
                fastcgi_param   SCRIPT_FILENAME  $request_filename;
                include         fastcgi_params;
        }

        location ~* \.(jpg|jpeg|gif|png|bmp|ico|pdf|flv|swf|exe|html|htm|txt|css|js) {
                add_header        Cache-Control public;
                add_header        Cache-Control must-revalidate;
                expires           7d;
                access_log off;
        }
}

为什么具有已知文件扩展名 ( ) 的 url 不能像任何其他 url 一样/myroute.php访问我的文件?index.php

4

1 回答 1

5

myroute.php在您的服务器上不存在。

Nginxlocation指令按此顺序检查

  1. 带有“=”前缀的指令与查询完全匹配(文字字符串)。如果找到,则停止搜索。
  2. 所有剩余的带有常规字符串的指令。如果此匹配使用“^~”前缀,则搜索停止。
  3. 正则表达式,按照它们在配置文件中定义的顺序。
  4. 如果 #3 产生匹配,则使用该结果。否则,使用来自 #2 的匹配

这意味着您的myroute.php请求将由~ \.php$location 块处理,这会根据您的 try_files 指令导致 404。

要解决这个问题,您需要使您的位置指令更具体(例如~ index\.php$),或者完全像在location /. 使用重写也可以解决您的问题。

编辑:

了解 nginx 选择位置块而不是其他位置块的顺序很重要。在nginx wiki上查看更多信息

关于您的问题,我认为最简单的解决方案是使用 try_files

    try_files $uri $uri/ /index.php?q=$uri&$args;

在你的location ~ \.php$ {location ~* \.(jpg|jpeg|gif|png|bmp|ico|pdf|flv|swf|exe|html|htm|txt|css|js) {块中

  • 注意:不要忘记try_files $uri =404.php$块中删除旧的

您的最终 conf 文件现在应该如下所示

server {
    listen          80;
    server_name     domain.com;
    root            /var/www/path/public;

    charset utf-8;
    gzip on;

    #access_log  logs/host.access.log  main;

    location / {
            index index.html index.php index.htm;
            try_files $uri $uri/ /index.php?q=$uri&$args;
    }

    location ~ \.php$ {
            try_files $uri $uri/ /index.php?q=$uri&$args;
            fastcgi_pass    unix:/var/run/php5-fpm.sock;
            fastcgi_index   index.php;
            fastcgi_param   SCRIPT_FILENAME  $request_filename;
            include         fastcgi_params;
    }

    location ~* \.(jpg|jpeg|gif|png|bmp|ico|pdf|flv|swf|exe|html|htm|txt|css|js) {
            try_files  $uri $uri/ /index.php?q=$uri&$args;
            add_header        Cache-Control public;
            add_header        Cache-Control must-revalidate;
            expires           7d;
            access_log off;
    }
 }
于 2013-11-11T21:54:46.863 回答