charmeleon
charmeleon

Reputation: 2755

Mapping subdomains in nginx is not working

I'm setting up some PHP subdomains, and I'm having a hard time getting nginx to do what I want. I'm trying to send each subdomain to a different part of the application. Here's what my file, called id.conf looks like (it's in the sites-enabled directory):

map $http_host $app {
    'api.id.dev'        'api/public';
    'www.id.dev'        'www/public';
}

server {
    set $base /Users/dev/www/id/apps;
    server_name  ~^(?<subdomain>.+)\.id\.dev$;
    index index.html index.htm index.php;
    root $base/$app;
    charset utf-8;
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    access_log off;
    client_max_body_size 100m;
    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param APP_ENV local;
    }
}

server {
    server_name id.dev;
    rewrite ^ http://www.id.dev$request_uri permanent;
}

I have the correct mapping for these subdomains in my /etc/hosts, and I see this error in the nginx error log:

2016/04/24 00:26:32 [error] 5691#0: *5 directory index of "/Users/dev/www/id/apps//" is forbidden, client: 127.0.0.1, server: ~^(?<subdomain>.+)\.id\.dev$, request: "GET / HTTP/1.1", host: "api.id.dev"

Which shows that the host is there, and it's reading the conf file, but it doesn't seem to be matching the http host to the correct directory. (Also, the directories for these subdomains have an index.php file)

What is the issue here? I have another config file that is doing the same thing, and it is working. In fact, I can load a separate tab and load those other sites, but it doesn't seem to be working for this project (and I've verified the file paths a ton of times already)

Upvotes: 0

Views: 1216

Answers (2)

charmeleon
charmeleon

Reputation: 2755

I worked it out. It turned out that the variable $app was conflicting with the other file using the same variable name for the map directive. I renamed the variable to $name in id.conf, first in the map:

map $http_host $name {
    'api.id.dev'        'api/public';
    'www.id.dev'        'www/public';
}

then I changed root $base/$app; to root $base/$name;, reloaded nginx with sudo nginx -s reload in the terminal, and now it works perfectly.

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174758

I think your matching is not working correctly, try this:

set $domain $host;

if ($domain ~ "^(.[^.]*)\.dev$") {
    set $domain $1;
    set $servername "${domain}.dev";
}

if ($domain ~ "^(.*)\.(.[^.]*)\.dev$") {
    set $subdomain $1;
    set $domain $2;
    set $servername "${subdomain}.${domain}.dev";
}

Upvotes: 0

Related Questions