I have a website (developed in ruby on rails + angularJS and running on nginx + unicorn) where users can access few pages through differents URIs. For example, www.example.com/1234 and 1234.example.com load the same content.

The problem is links in 1234.example.com don't work properly, because these links depend on host, and 1234.example.com is not a valid host for that.

My nginx conf for subdomains is like that:

server {
    root /var/www/example.com/current/public;
    server_name 1234.example.com;

    try_files $uri/index.html $uri.html $uri @app;

    location / {
        add_header Set-Cookie qid=1234;
        proxy_pass https://www.example.com/1234;
        proxy_set_header X-Forwarded-For;
        proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
        proxy_redirect off;

    location /assets/ {
        alias /var/www/example.com/current/public/assets/;
        proxy_pass https://www.example.com;

    location ~ /(library|categories) {
       proxy_pass https://www.example.com;

Cookie and location directives "/assets/" and "~ /(library|categories)" are required for load all content.

So, I need set host as 1234.example.com only for the "/" location, but in any other case, the host sould be www.example.com.

Thank you so much.


An nginx way would be to use a map:

map $http_host $sitevar {
   1234.example.com "1234";
   default "";

if ($sitevar = 1234) {
   rewrite ^ /1234 permanent;

and set your cookie with qid=$sitevar

You then set your server_name to a wildcard:

server_name .example.com;

For that matter you could do that and handle the routing in code as you can pass the variable as part of the request.

  • I can not use rewrite because I need keep url as "1234.example.com" when visitor has typed 1234.example.com.
    – MAL
    Nov 28 '17 at 12:23
  • Thinking about it, using proxy_pass should work but you may have to pass $uri to get the right page. However, I would also look at making the code respond to hostnames correctly as it would make life a lot easier. Nov 28 '17 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.