Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping subdomains to URLs with nginx

I'm very new to nginx, so forgive me if my explanations are off. I'll do my best to explain what I am trying to achieve.

Using WordPress and nginx, I would like user accounts to be mapped to a subdomain of the main domain. For example, if the user creates an account called "sample", the subdomain for that user would be sample.example.com.

When the user goes to sample.example.com, the subdomain should be mapped to example.com/sample/. Similarly, if a user visits sample.example.com/account/, it should map to example.com/sample/account/, and so on and so forth. It should be noted that the example.com/sample/ URLs are rewrites of this type of structure: example.com/index.php?user=sample.

There are also a few reserved subdomains that should not be redirected, such as cdn and admin. They should be ignored by these rules if they are requested.

How can I achieve this automatically when a user creates an account? The goal here is automation - set it up once correctly and not worry about it. Since I have literally just started working with nginx a few days ago, I'm not sure where to start at all. Any advice to move me in the right direction would be incredibly helpful. Here is my current config file for the domain:

server {
    listen          80;
    server_name     www.example.com;
    rewrite     ^(.*) $scheme://example.com$1 permanent;
}

server {
    listen          443 ssl;
    server_name     www.example.com;
    rewrite         ^(.*) $scheme://example.com$1 permanent;
}

server {
    listen      80;
    server_name example.com;

    access_log  /var/www/example.com/logs/access.log;
    error_log   /var/www/example.com/logs/error.log;

    root        /var/www/example.com/public;
    index       index.php;

    location / {
        try_files $uri $uri/ @wordpress /index.php?q=$request_uri;
    }

    location @wordpress {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_param SCRIPT_FILENAME /var/www/example.com/public/index.php;
        include /etc/nginx/fastcgi_params;
        fastcgi_param SCRIPT_NAME /index.php;
    }

    # Pass the PHP scripts to FastCGI server listening on UNIX sockets.
    #
    location ~ \.php$ {
        try_files $uri @wordpress;
        fastcgi_pass   unix:/var/run/php5-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /var/www/example.com/public$fastcgi_script_name;
        include        fastcgi_params;
    }
}

server {
    listen                      443 ssl;
    ssl                         on;
    keepalive_timeout           70;
    server_name                 example.com;
    ssl_certificate             ssl/example.com.chained.crt;
    ssl_certificate_key         ssl/example.key;
    ssl_protocols               SSLv3 TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers                 HIGH:!aNULL:!MD5;
    ssl_session_cache           shared:SSL:10m;
    ssl_session_timeout         10m;
    ssl_prefer_server_ciphers   on;

    root        /var/www/example.com/public;
    index       index.php;

    location / {
        try_files $uri $uri/ @wordpress /index.php?q=$request_uri;
    }

    location @wordpress {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_param SCRIPT_FILENAME /var/www/example.com/public/index.php;
        include /etc/nginx/fastcgi_params;
        fastcgi_param SCRIPT_NAME /index.php;
    }

    # Pass the PHP scripts to FastCGI server listening on UNIX sockets.
    #
    location ~ \.php$ {
        try_files $uri @wordpress;
        fastcgi_pass   unix:/var/run/php5-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /var/www/example.com/public$fastcgi_script_name;
        include        fastcgi_params;
    }
}

I understand that what I am trying to achieve probably needs to go into the /etc/nginx/nginx.conf file if I want it to be automated, and I am actively trying to learn how to achieve this. I'm just stuck where I am at now and am looking for any advice/help that would point me in the right direction. I'm eager to learn!

like image 265
Thomas Avatar asked Feb 05 '13 16:02

Thomas


People also ask

How do I point a subdomain to a URL?

Under Modify a Subdomain, locate the domain you want to redirect, then click its Manage Redirection link on the right. In the text box, type the URL you would like visitors to be redirected to if they go to the subdomain sample1.hgexample.com. Click Save. You will see the redirected URL under the Redirection column.


2 Answers

ANSWER

After days of searching, tweaking, and configuring, I've gotten down the code needed to map subdomains to URLs exactly like in my example. Here is my vhost for example.com: https://gist.github.com/thomasgriffin/4733283

server {
    listen      80;
    listen      443 ssl;
    server_name ~^(?<user>[a-zA-Z0-9-]+)\.example\.com$;

    location / {
        resolver            8.8.8.8;
        rewrite             ^([^.]*[^/])$ $1/ permanent;
        proxy_pass_header   Set-Cookie;
        proxy_pass          $scheme://example.com/user/$user$request_uri;
    }
}

server {
    listen          80;
    listen          443 ssl;
    server_name     www.example.com;
    return          301 $scheme://example.com$request_uri;
}

server {
    listen      80;
    server_name example.com;

    access_log  /var/www/example.com/logs/access.log;
    error_log   /var/www/example.com/logs/error.log;

    root        /var/www/example.com/public;
    index       index.php;

    location / {
        try_files $uri $uri/ @wordpress /index.php?q=$request_uri;
    }

    location @wordpress {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include /etc/nginx/fastcgi_params;
        fastcgi_param SCRIPT_NAME /index.php;
    }

    # Pass the PHP scripts to FastCGI server listening on UNIX sockets.
    #
    location ~ \.php$ {
        try_files $uri @wordpress;
        fastcgi_pass   unix:/var/run/php5-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

server {
    listen                      443 ssl;
    ssl                         on;
    keepalive_timeout           70;
    server_name                 example.com;
    ssl_certificate             ssl/example.com.chained.crt;
    ssl_certificate_key         ssl/example.key;
    ssl_protocols               SSLv3 TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers                 HIGH:!aNULL:!MD5;
    ssl_session_cache           shared:SSL:10m;
    ssl_session_timeout         10m;
    ssl_prefer_server_ciphers   on;

    root        /var/www/example.com/public;
    index       index.php;

    location / {
        try_files $uri $uri/ @wordpress /index.php?q=$request_uri;
    }

    location @wordpress {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include /etc/nginx/fastcgi_params;
        fastcgi_param SCRIPT_NAME /index.php;
    }

    # Pass the PHP scripts to FastCGI server listening on UNIX sockets.
    #
    location ~ \.php$ {
        try_files $uri @wordpress;
        fastcgi_pass   unix:/var/run/php5-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

The main chunk of the mapping is done in the first server block. I'm targeting any subdomain (I will have already weeded out restricted subdomains with other non-relevant code) and rewriting it to ensure that it has a trailing slash to avoid any internal redirects by WordPress for URLs without a trailing slash. From there, the resolver directive is required to resolve URLs defined in proxy_pass, so I am resolving with Google's DNS. I'm also using the proxy_pass_header directive to send over cookies in order to keep WordPress login authentication in tact. proxy_pass defines the URL to map to.

It should also be noted that if you want to use login authentication as well with subdomains, you need to define your custom cookie domain in wp-config.php like this:

define('COOKIE_DOMAIN', '.example.com');

And that should be it. You can now enjoy URLs like subdomain.example.com that map to example.com/user/subdomain/ or whatever you want. From there, you can utilize WordPress' Rewrite API to map the mapped URL to specific query args that can be sent to $wp_query for loading custom templates, etc.

like image 137
Thomas Avatar answered Oct 28 '22 02:10

Thomas


the following should do it:

server {
  listen 80; listen 443;
  server_name *.example.com;

  if ($host ~ "^(.*)\.example\.com$" ) { set $subdomain $1;}
  rewrite ^ $scheme://example.com/$subdomain/$request_uri permanent;
}

(as an aside: the regex ^ matches all url's the most efficiently, and the standard nginx variable $request_uri holds the uri including arguments so you don't need the (.*) group in the rewrite)

additionally add a second serverblock for the domains you don't want redirected:

server {
  listen 80; listen 443;
  server_name cdn.example.com admin.example.com;
  # do whatever with the requests of the reserved subdomains;
}
like image 43
cobaco Avatar answered Oct 28 '22 03:10

cobaco