【问题标题】:Convert Apache VirtualHost to nginx Server Block for Dynamic Subdomains将 Apache VirtualHost 转换为用于动态子域的 nginx 服务器块
【发布时间】:2015-08-22 15:21:54
【问题描述】:

我有一个在 Apache 上运行的 Web 应用程序,其中虚拟主机文件配置为将请求路由到子域到特定文件夹。不必每次创建子域时都修改主机文件,这允许我将 URL 动态路由到相关文件夹(如果文件夹不存在,则使用包罗万象)-

<VirtualHost *:8080>
    ServerName localhost.com
    ServerAlias *.localhost.com
    VirtualDocumentRoot "/var/www/clients/%1"
    ErrorLog "logs\errors.log"
    <directory "/var/www/clients/%1">
        Options Indexes FollowSymLinks
        AllowOverride all
        Order Deny,Allow
        Deny from all
        Allow from all
    </directory>
</VirtualHost>

我正在尝试将上述内容转换为 nginx,但找不到正确的逻辑来从 URL 中提取子域,然后在配置文件中设置 root 变量。

谁能帮我为 nginx 编写 server {} 块,如果 root 路径不存在,还要加上一个 catch-all 块?

【问题讨论】:

  • server { server_name ~^(.*)\.localhost\.com$ ; root var/www/clients/$1; }

标签: apache dynamic nginx vhosts


【解决方案1】:

在 server_name 中使用命名的正则表达式捕获,您可以稍后参考。

server {
    listen 8080;
    server_name ~^(?<subdir>.*)\.localhost\.com$ ;

    set $rootdir "/var/www/clients";
    if ( -d "/var/www/clients/${subdir}" ) { set $rootdir "/var/www/clients/${subdir}"; }
    root $rootdir;
}

您所做的是将默认根目录设置为变量$rootdir,然后如果$subdir 设置的子目录存在,则覆盖它。

【讨论】:

  • 非常感谢。不幸的是,它没有按预期工作。在/var/www/clients 目录下,我有一个目录client1,其中包含index.html。我在 catch-all 目录下也有一个 index.html。如果我导航到 http://client1.localhost.com nginx 将返回包罗万象的页面(即直接转到 $rootdir 而不是 $rootdir/client1
  • 我已经切换了设置默认的顺序。它现在应该可以工作了。
  • 我已将server 块更改为server { listen 8080; server_name *.localhost.com; if ( -d "/var/ww/clients/$subdir" ) { set $rootdir "/var/www/clients/$subdir"; } if ( $rootdir == "" ) { set $rootdir '/var/www/clients'; } root $rootdir; } ,但是当我尝试使用sudo service nginx restart 重新启动nginx 时它失败了。
  • 谢谢。我继续测试并发现错误。我还通过您尝试的示例进行了简化。
猜你喜欢
  • 2021-07-12
  • 1970-01-01
  • 2021-10-03
  • 2014-09-24
  • 1970-01-01
  • 2017-01-14
  • 2023-04-04
  • 1970-01-01
  • 2015-05-21
相关资源
最近更新 更多