jM2*_*.me 20 virtualhost nginx dynamic
尝试使用nginx大约一个小时试图设置大规模动态虚拟主机.如果你曾经在apache中做过,你知道我的意思.
目标是为办公室中的少数人提供动态子域名(超过50个)
小智 62
也许这样做可以让你达到你想要的目的:
server {
root /sites/$http_host;
server_name $http_host;
...
}
Run Code Online (Sandbox Code Playgroud)
我喜欢这个,因为我可以随意创建网站,只需创建以域命名的新目录并将DNS指向服务器ip.
Gla*_*vić 16
你将需要一些脚本知识将这些放在一起,我会使用php,但如果你擅长bash脚本使用它.我会这样做:
首先创建一些文件夹(/usr/local/etc/nginx/domain.com/).
在主nginx.conf中添加命令: include /usr/local/etc/nginx/domain.com/*.conf;
此文件夹中的每个文件都应该是不同的vhost名称subdomain.conf.
你不需要重启nginx服务器以便配置采取行动,你只需要重新加载它:/usr/local/etc/rc.d/nginx reload
或者,您只能创建一个conf文件,其中应设置所有vhost.这可能更好,以便nginx不需要加载50个文件,但只需要一个....
如果你有脚本问题,那么问一下这个问题......
根据user2001260的答案(稍后由partlov编辑),这是我的结果。
请记住,这是针对位于本地虚拟机上的开发服务器.dev的,每个域的末尾都使用前缀。如果要删除它或使用其他东西,可以编辑或完全删除指令中的\.dev零件server_name。
server {
listen 80 default_server;
listen [::]:80 default_server;
# Match any server name with the format [subdomain.[.subdomain...]].domain.tld.dev
server_name ~^(?<subdomain>([\w-]+\.)*)?(?<domain>[\w-]+\.[\w-]+)\.dev$;
# Map by default to (projects_root_path)/(domain.tld)/www;
set $rootdir "/var/www/$domain/www";
# Check if a (projects_root_path)/(subdomain.)(domain.tld)/www directory exists
if (-f "/var/www/$subdomain.$domain/www"){
# in which case, set that directory as the root
set $rootdir "/var/www/$subdomain.$domain/www";
}
root $rootdir;
index index.php index.html index.htm index.nginx-debian.html;
# Front-controller pattern as recommended by the nginx docs
location / {
try_files $uri $uri/ /index.php;
}
# Standard php-fpm based on the default config below this point
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
location ~ /\.ht {
deny all;
}
Run Code Online (Sandbox Code Playgroud)
}
中的正则表达式server_name捕获变量subdomain和domain。该subdomain部分是可选的,可以为空。我已将其设置为默认情况下,如果您有子域,则说admin.mysite.com根设置为与相同mysite.com。这样,同一个前端控制器(在我的例子中index.php)可以基于子域进行路由。但是,如果您要将完全不同的应用程序保留在一个子域中,则可以有一个admin.mysite.com目录,它将使用该目录来调用admin.mysite.com。
小心:采用if当前nginx的版本是不鼓励的,因为它增加了对每个请求额外的处理开销,但它应该是在开发环境,这是该配置是很好用的罚款。在生产环境中,建议不要使用大规模虚拟主机配置,而应分别配置每个站点,以实现更多控制和更好的安全性。