我是 Nginx 新手,我正在尝试让子域正常工作。
我想做的是获取我的域名(我们称之为
example.com
)并添加:
sub1.example.com
,sub2.example.com
,还有www.example.com
可用。我知道如何使用 Apache 做到这一点,但 Nginx 确实令人头疼。
我正在运行 Debian 6。
我当前的/etc/nginx/sites-enabled/example.com:
server {
server_name www.example.com example.com;
access_log /srv/www/www.example.com/logs/access.log;
error_log /srv/www/www.example.com/logs/error.log;
root /srv/www/www.example.com/public_html;
location / {
index index.html index.htm;
}
location ~ \.php$ {
include /etc/nginx/fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name;
}
}
它正在努力为 example.com 和 www.example.com 提供服务。
我尝试在同一个文件中添加第二个服务器块,例如:
server {
server_name www.example.com example.com;
access_log /srv/www/www.example.com/logs/access.log;
error_log /srv/www/www.example.com/logs/error.log;
root /srv/www/www.example.com/public_html;
server {
server_name sub1.example.com;
access_log /srv/www/example.com/logs/sub1-access.log;
error_log /srv/www/example.com/logs/sub1-error.log;
root /srv/www/example.com/sub1;
}
location / {
index index.html index.htm;
}
location ~ \.php$ {
include /etc/nginx/fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name;
}
}
没有运气。有任何想法吗?我非常感谢任何反馈。
错误是将服务器块放在服务器块中,您应该关闭主服务器块,然后为子域打开一个新服务器块
server {
server_name example.com;
# the rest of the config
}
server {
server_name sub1.example.com;
# sub1 config
}
server {
server_name sub2.example.com;
# sub2 config
}
使用 sub1.example.com 和 sub2.example.com 为 DNS 提供商中的每个添加 A
字段设置服务器。最后保留 example.com
如下
server {
server_name sub1.example.com;
# sub1 config
}
server {
server_name sub2.example.com;
# sub2 config
}
server {
server_name example.com;
# the rest of the config
}
sudo systemctl restart nginx
您只需添加以下行来代替您的 server_name
server_name xyz.com *.xyz.com;
并重新启动Nginx。就是这样。
您必须为您的子域创建另一个带有服务器块的 nginx 配置文件。像这样:
/etc/nginx/sites-enabled/subdomain.example.com
有一个非常可定制的解决方案,具体取决于您的服务器实现:
单个 nginx“sites”文件中有两个(或更多)子域?如果您拥有通配符 TLS 证书,因此想要维护一个 nginx 配置文件,那就太好了。全部使用相同的服务但不同的端口? (想想同时运行的不同应用程序版本,每个版本在本地侦听不同的端口)
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name ~^(?<sub>.+).example.com;
# default app (the "default" ports, good for the "old" app)
set $app 19069;
set $app-chat 19072;
# new app
# new.example.com
if ( $sub = "new" ) {
set $app 18069;
set $app-chat 18072;
}
# upstreaming
location / {
proxy_redirect off;
proxy_pass http://127.0.0.1:$app;
}
location /longpolling {
proxy_pass http://127.0.0.1:$app-chat;
}
我知道性能会“糟糕”,但话又说回来,由于决定全部使用一台服务器,这就像抱怨经济箱不能像公共汽车那样运送那么多人,因为这辆小汽车有一个“沉重”的车顶行李架在它上面。
正则表达式专家可能会提高此类自定义解决方案的性能,特别是因为它可以省略 CPU 昂贵的“if”条件语句。
也许这可以帮助那些面临挑战的人,这让我整天都在苦苦挣扎。 首先,如果您安装了 SSL,请将其删除(删除更好),这将有助于重置先前破坏子域配置的配置。
在etc/nginx/.../默认文件中 创建一个新的服务器块
server {
listen 80;
server_name subdomain.domain.com;
location /{
proxy_pass http://localhost:$port;
}
}