nginx - two subdomain configuration

你说的曾经没有我的故事 提交于 2019-11-28 17:21:11

问题


I'm new to Nginx and I'm trying to get subdomains working.

What I would like to do is take my domain (let's call it example.com) and add:

  • sub1.example.com,
  • sub2.example.com, and also have
  • www.example.com available.

I know how to do this with Apache, but Nginx is being a real head scratcher.

I'm running Debian 6.

My current /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;
    }
}

It is working to serve example.com and www.example.com.

I have tried to add a second server block in the same file like:

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;
        }
}

No luck. Any ideas? I'd super appreciate any feedback.


回答1:


The mistake is putting a server block inside a server block, you should close the main server block then open a new one for the sub domains

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
}



回答2:


You just need to add the following line in place of your server_name

server_name xyz.com  *.xyz.com;

And restart Nginx. That's it.




回答3:


You'll have to create another nginx config file with a serverblock for your subdomain. Like so:

/etc/nginx/sites-enabled/subdomain.example.com


来源:https://stackoverflow.com/questions/17568981/nginx-two-subdomain-configuration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!