Welcome! Log In Create A New Profile

Advanced

dynamic virtual host and sub domains

Posted by aconway 
dynamic virtual host and sub domains
August 23, 2013 07:51PM
I trying out NGinx for the first time after having a hard time trying to figure out this issue on Apache.

I want to have a dynamic virtual host and dynamic sub domains

So, I can have a domain and folder structure like the following. The redirect is working, but not the subdomains.

www.domain.com => /var/www/vhosts/domain.com/htdocs/www
domain.com => redirect to www.domain.com
foo.domain.com => /var/www/vhosts/domain.com/htdocs/foo

www.another.domain.co.uk => /var/www/vhosts/another.domain.co.uk/htdocs/www
another.domain.co.uk => redirect to www.another.domain.co.uk
bar.another.domain.co.uk => /var/www/vhosts/domain.com/htdocs/bar
!-d baz.another.domain.co.uk => redirect to www.another.domain.co.uk

this is what I have so far

http {

server {
listen 80;
index index.html index.htm index.php;
set $basepath "/var/www/vhosts";
set $domain $host;

# get the subdomain
if ( $domain ~ "^(.+?)\.(.*)" ) {
set $domain $2;
set $sub $1;
}

set $root $basepath/$domain/htdocs/www;

# if the domain is missing a subdomain then the default path will fail
if ( !-d $root ) {
rewrite ^(.*) http://www.$host$1;
}

# use the subdomain path
if ( !-d $basepath/$domain/htdocs/$sub ) {
rewrite ^(.*) http://www.$host$1;
}

location / {
root $root;
}

location ~ \.php$ {
root $root;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME $request_filename;
}

}
}



Edited 1 time(s). Last edit at 08/23/2013 07:59PM by aconway.
Re: dynamic virtual host and sub domains
August 24, 2013 01:56AM
It looks like this might be working for me.

http {

server {
listen 80;
index index.html index.htm index.php;
set $basepath "/var/www/vhosts";
server_name ~^(?<sub>.+?)\.(?<domain>.+)$;

set $root $basepath/$domain/htdocs/www;

# if the domain is missing a subdomain then the default path will fail
if ( !-d $basepath/$domain/htdocs/www ){
rewrite ^ $scheme://www.$host$uri redirect;
}

set $root $basepath/$domain/htdocs/$sub;

# sub domain path doesn't exist redirec to default
if ( !-d $root ){
rewrite ^ $scheme://www.$domain$uri redirect;
}


location / {
root $root;
}

location ~ \.php$ {
root $root;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME $request_filename;
}

}
}
Sorry, only registered users may post in this forum.

Click here to login

Online Users

Guests: 129
Record Number of Users: 8 on April 13, 2023
Record Number of Guests: 500 on July 15, 2024
Powered by nginx      Powered by FreeBSD      PHP Powered      Powered by MariaDB      ipv6 ready