nginx $hostMap与subdir_path

1sbrub3j  于 2023-08-03  发布在  Nginx
关注(0)|答案(1)|浏览(115)

我试着用nginx解决这个问题:
我在/var/www/html下有多个文件夹:

/var/www/html/abc.example.com
/var/www/html/cde.example.com
/var/www/html/ghi.example.com

字符串
在nginx中如何配置$hostMap到目录,这样如果我打开abc.example.com,它会自动重定向到abc.example.com文件夹。另外,如果我添加www.example.com,我不想修改nginx配置文件xyz.example.com,所以$hostMap应该Map到subdir_path,并且只有当$host= directory path时才有效。
如果我打开mnw.example.com,如果同名文件夹不存在..如果不应该工作。

map $http_host $subdir {
    "~^(www\.)?(?<domain>.+)$"    $domain;
}

server {
    listen 80;
    server_name _;

    root /var/www/html;

    location / {
        # Remove the www prefix (optional)
        if ($http_host ~* "^www\.(.*)$") {
            set $host_without_www $1;
            rewrite ^(.*)$ $scheme://$host_without_www$1 permanent;
        }

        # Serve the content from the corresponding directory
        try_files $uri $uri/ @subdir_index;
    }

    location @subdir_index {
        # Construct the path to the corresponding directory
        set $subdir_path "/var/www/html/$subdir$uri";

        # Check if the directory corresponding to the host exists
        if (-d $subdir_path) {
            # Serve the index.html from the corresponding directory
            rewrite ^ $subdir_path/index.html last;
        }

        # Serve the default index.html
        rewrite ^ /index.html last;
    }
}

7ajki6be

7ajki6be1#

我能够用非常简单的设置解决这个问题。@richard Smith给出的改进答案

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        #
        # include snippets/snakeoil.conf;

        root /var/www/html/$http_host;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;
        location / {
                try_files $uri $uri/ /index.html;
        }
}

字符串

相关问题