Nginx
有沒有辦法在 NGINX 中動態轉發子域?
我已經做了所有我能做的Google搜尋,但沒有運氣。我試圖弄清楚如何為使用者創建命名空間,比如 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; }
又一整天的Google搜尋,我發現了這個寶石:
####################### 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 ####################