有没有办法在 NGINX 中动态转发子域名?

有没有办法在 NGINX 中动态转发子域名?

我已经用尽了所有能用到的谷歌搜索,但还是没找到。我试图弄清楚如何为用户创建一个命名空间,比如 user.mysite.com,并将其重定向到他/她的文件夹 (mysite.com/user)。有没有办法让 nginx 将所有子域转发到它们各自的文件夹?我这样做的原因是我希望能够动态创建这样的子域,而无需重新启动 nginx。

仅供参考,我的 nginx.conf 文件现在看起来像这样。

server
{

# add www.
if ($host ~ ^(?!www)) {
    rewrite ^/(.*)$ http://www.$host/$1 permanent;
}


server_name www.mydomain.com;

access_log /var/log/nginx/mydomain.com.access.log;

    error_log /var/log/nginx/mydomain.com.error.log;

root /usr/share/nginx/mydomain.com/;

index index.php index.html index.htm;

# use fastcgi for all php files
location ~ \.php$
{
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

# deny access to apache .htaccess files
location ~ /\.ht
{
    deny all;
}
}

这是我发现的一小段代码,它将把所有子域重定向到 www.mydomain.com。如果它可以重定向到它们各自的目录,那正是我所需要的。

# remove subdomain
if ($host ~ "^www\.(.*?)\.(.{3,}\.([a-z]{2}\.[a-z]{2}|[a-z]{2,4}))$") {
    set $host_without_sub $2;
    rewrite ^/(.*)$ http://www.$host_without_sub/$1 permanent;
}

答案1

经过一整天的谷歌搜索,我发现了这颗宝石:

http://publications.jbfavre.org/web/nginx-vhosts-automatiques-avec-SSL-et-authentification-version2.en

#######################  Magic  RewriteRules  #######################

uninitialized_variable_warn off;

##### Rewrite rules for domain.tld => www.domain.tld #####
if ($host ~* ^([^.]+\.[^.]+)$) {
    set $host_without_www $1;
    rewrite ^(.*) $scheme://www.$host_without_www$1 permanent;
}

##### Rewrite rules for subdomains with automatic SSL support #####
set $redirect_ssl 'no';
if ($host ~* ^(.*)\.([^.]+\.[^.]+)$) {
    set $ssl_subdomain $1;
    set $host_without_www $1.$2;
}
if (-e $document_root/config/ssl/$ssl_subdomain) {
    set $redirect_ssl 'yes';
}
if ($scheme = 'https') {
    set $redirect_ssl 'no';
}
if ($redirect_ssl = 'yes') {
    rewrite ^(.*) https://$ssl_subdomain.$host_without_www$1 permanent;
}

##### Rewrite rules for automatic authentication #####
if ($host ~* ^([^.]+)\.[^.]+\.[^.]+$) {
    set $auth_subdomain $1;
}
if (-e $document_root/config/auth/$auth_subdomain) {
    rewrite ^(.*)$ /auth$1;
    break;
}

##### Rewrite rules for automatic subdirectory rewriting #####
set $redirect_subdir 'yes';
if ($redirect_subdir_done = 'yes') {
    set $redirect_subdir 'no';
}
if ($host ~* 'www\.[^.]+\.[^.]+$') {
    set $redirect_subdir 'no';
}
if ($host ~* ^([^.]+)\.[^.]+\.[^.]+$) {
    set $subdir_domain '$1';
}
if ($redirect_subdir = 'yes') {
    set $redirect_subdir_done 'yes';
    rewrite ^(.*)$  /$subdir_domain$1 break;
}

####################  End Of Magic RewriteRule  ####################

相关内容