2014-11-02 310 views
3

我在我的nginx配置文件中有以下内容,但它可以工作,但我不想列出每个文件扩展名。Nginx位置匹配除php之外的所有文件扩展名

location ~ \.(gif|jpg|png|css|js|ttf|woff|html|htm|unity3d) { 
    try_files $uri /images/default.gif; 
} 

有没有一种方法可以将此应用于除php文件之外的所有内容?

编辑:更新配置

主要文件:

server{ 
    listen 80 default_server; 

    server_name _; 
    root   /usr/share/nginx/html/$http_host; 
    index   index.php index.html index.htm; 

# location ~ \.(gif|jpg|png|css|js|ttf|woff|html|htm|unity3d|tpl) { 
#  try_files $uri /images/default.gif =404; 
# } 

    location ~ .+(?<!\.php)$ { 
     location ~ ^[^.]+\.[^.]+$ { 
      try_files $uri /images/default.gif =404; 
     } 

     location ~/{ 
      try_files $uri $uri/ /index.html; 
      include /usr/share/nginx/conf/mission13.io.conf; 
     } 

    } 

    location ~ \.php$ { 
     fastcgi_pass unix:/var/run/php5-fpm.sock; 
     fastcgi_index index.php; 
     fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 
     include fastcgi_params; 
    } 
} 

然后在包含的文件:

if ($http_host = groups.mission13.io) { 
    rewrite ^(.+)$ /index.php?path=$1; 
} 

回答

8

PCRE库

Nginx的使用PCRE library写在C. 有一个巨大的man page,有点难以理解有时,但相当详细。其中,你会发现前面/后面的功能,你会发现它们在Perl中。

模型正/负前方看/后面

正/负先行/后面允许如果它的一个部分/后面没有/由表达式之前匹配的字符串。查看表达式仅限于固定字符串,因为大多数实现都不可能向后应用正则表达式,因为您需要知道为此返回了多少个步骤。展望未来不会受到这种限制,因此您可以像通常那样使用正则表达式。

这里的手册页的相关章节:

LOOKAHEAD和后向断言

 (?=...)   positive look ahead 
    (?!...)   negative look ahead 
    (?<=...)  positive look behind 
    (?<!...)  negative look behind 

Each top-level branch of a look behind must be of a fixed length. 

可惜你不能捕捉前方看的字符串的结尾。

背后看在行动

所以,我们的第一次尝试将使用负的样子从字符串的结尾背后:

location ~ .+(?<!\.php)$ { 
    ... 
} 

这意味着“不以.php最后只能捕获串”。这与我们已经需要的非常接近。但还有一些东西需要添加才能使其按预期工作。

嵌套位置

事实上,没有什么保证,你将有包含在这一点上的文件扩展名的字符串。它可以是什么除了^.+\.php$。为了确保这是一个真正的文件后缀,彻底检查此限制的自然方法是使用嵌套位置块,其中限制性最强的部分是顶点。所以我们的配置现在看起来像下面。

location ~ .+(?<!\.php)$ { 
    location ~ ^[^.]+\.[^.]+$ { 
     try_files $uri /images/default.gif; 
    } 
} 

就是这样!

你的第二个问题

这里有您的文章更新的第二个问题后,我的话你面对(在其他404错误网址)。

由于~ .+(?<!\.php)$匹配一切,除了\.php$和位置嵌套时,你需要嵌套位置块/并将其转换为一个正则表达式匹配:

location ~ .+(?<!\.php)$ { 

    location ~ ^[^.]+\.[^.]+$ { 
     try_files $uri /images/default.gif; 
    } 

    location ~/{ 
     # your stuff 
    } 

} 

另外请注意,你可以用一个无限循环结了try_files $uri /images/default.gif;部分,因为try_files指令的最后一个参数是内部重定向或HTTP代码。因此,如果/images/default.gif未解析为文件,则该请求将通过该位置块10多次,直到nginx停止处理并返回HTTP 500.所以将其更改为try_files $uri /images/default.gif =404;

+0

非常好!但是当我尝试点击主页面('site.com')以外的页面('site.com/home')时,我得到了404。我将我的完整配置添加到该问题中。 – 2014-11-04 20:09:30

+0

@RyanNaddy请检查我的第二个问题的答案更新。 – 2014-11-04 21:21:13

+0

好吧,现在当我打开页面时,它会下载文件而不是显示它。我用新的配置文件更新了问题。 – 2014-11-05 16:37:48