大网数据广告活动
服务器运维问答

Is there a clean way of combining nginx location rules?

· 52CE 我爱测

Suppose that in my nginx server I want to accomplish these two requirements: 1) all *.php files are to be passed to the php interpreter 2) directory /private/ should require http authentication If I write location /private/ { aut…

问题原文

原帖链接 · leonbloy · CC BY-SA 4.0

Suppose that in my nginx server I want to accomplish these two requirements:

1) all *.php files are to be passed to the php interpreter

2) directory /private/ should require http authentication

If I write

location /private/  {
  auth_basic            "Restricted";
  ....
}

location ~ \.php$ {
    fastcgi_pass   127.0.0.1:9000;
     .... more settings
}

then (if I'm not mistaken) the authentication will only apply to non php files. If instead I add the ^~ flag to the location block, then I loose the php location. This is logical, because nginx only matches one location block.

It seems that the only option left is to use a nested location:

location /private/  {
  auth_basic            "Restricted";
  ....
    location ~ \.php$ {
       fastcgi_pass   127.0.0.1:9000;
         .... more settings
    }
}

location ~ \.php$ {
    fastcgi_pass   127.0.0.1:9000;
     .... more settings
}

This looks rather clumsy and fragile to me: each time I add a protected dir location (or some dir with some special setting), I must remember to add nested locations for PHP (and perhaps other file types). But it seems to be the only way to go. Is this so? Can anyone suggest a better solution?

已采纳解答

原帖链接 · moebius_eye · CC BY-SA 3.0

Unfortunately, no. There is no cleaner way, as explained here, here and in the documentation

But, you should probably use a separate file for your php configuration, that way, all you have to do is this:

location /private/  {
    auth_basic            "Restricted";
    ....
    location ~ \.php$ {
        include phpconf.conf;
    }
}

location ~ \.php$ {
   include phpconf.conf;
}

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2014-06-22)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0 / CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。