Nginx子目录中的单独应用

时间:2019-04-16 12:21:39

标签: nginx nginx-location

我正在尝试将应用程序从apache服务器迁移到nginx。问题是子目录中有多个应用程序,我找不到配置服务器的正确方法。

我需要什么:

  • www.example.com/srv/app服务
  • www.example.com/sub1/srv/app/sub1服务
  • www.example.com/sub2/srv/app/sub2服务

每个应用程序都需要相同的配置,因此我将其提取为摘要:

# snippets/app.conf

index index.php index.html index.htm index.nginx-debian.html;

location /system {
    return 403;
}

# [a couple of other 403s excluded]

# Pass non-file URI to index.php
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

# Use PHP
location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
}

# Hide .htaccess
location ~ /\.ht {
    deny all;
}

在主服务器文件中:

# [non-www and http redirects]

server {
    # [listen directives]

    server_name www.example.com;

    root /srv/app;

    include snippets/app.conf;

    location /sub1 {
        root /srv/app/sub1;
        include snippets/app.conf;
    }

    # [other sub-apps included in the same way]

    # [ssl stuff]
}

但是,这给了我一个错误:

  

nginx:[emerg]位置“ / system”在/etc/nginx/snippets/app.conf:5中的位置“ / sub1”之外

从错误显而易见,/system被解释为“绝对” www.example.com/system,而不是嵌套的www.example.com/sub1/system。我可以以某种方式指定将嵌套位置视为相对位置吗?或者我只需要为每个更改前缀的子应用重复整个接近相同的配置?

1 个答案:

答案 0 :(得分:0)

事实证明,大多数重复在nginx中都是不必要的。

将fastcgi用于.php并隐藏/.ht文件的指令已经是正则表达式,因此它们会影响所有内容。只需指定一次index就足够了,如果我只想使用index.php,那么那里的默认值是多余的。

由于所有应用程序都以与Web相同的方式嵌套在文件系统上,因此也无需指定root。

令我惊讶的是,location ^~ /(system|data)/ { ... }不仅匹配www.example.com/system/,而且匹配www.example.com/sub1/system/。我认为^~仅在位置开始与正则表达式匹配时才应匹配...

# [non-www and http redirects]

server {
    # [listen directives]

    server_name www.example.com;

    root /srv/app;

    index index.php;

    location ^~ /(system|data)/ {
        return 403;
    }

    # Use PHP
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    }

    # Pass non-file URI to index.php for all locations
    location /sub1/ {
        try_files $uri $uri/ /sub1/index.php?$query_string;
    }

    location /sub2/ {
        try_files $uri $uri/ /sub2/index.php?$query_string;
    }

    # [other sub-apps included in the same way]

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ /\.ht {
        deny all;
    }

    # [ssl stuff]
}

我还尝试用

替换单独的位置
location ^~ /(sub1|sub2)/ {
    try_files $uri $uri/ /$1/index.php?$query_string;
}`

但没有成功-这个位置以某种方式从未匹配,而是所有内容都传递给了基址中的/index.php