fractal5
fractal5

Reputation: 2132

Nginx - Serving different favicons for each subdomain sharing the same declaration

I have 2 sites: abc.domain.com & def.domain.com

Being subdomains, they share the same cert and also the same root folder. Essentially they go to the same site, but for different clients.

server {
    listen 443 ssl;
    server_name abc.domain.com def.domain.com;

    root /var/www/project;

    location /favicon.ico {
        alias /var/www/project/src/favicon_abc.ico;
        #use /var/www/project/src/favicon_def.ico for def.domain.com;
    }
}

Can I use a different favicon for each site, without creating a separate declaration?

Upvotes: -1

Views: 38

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15470

Sure. You can use either some kind of automatic host-to-filename conversion, e.g. (using the $host variable):

server {
    ...
    server_name abc.example.com def.example.com;
    ...
    location = /favicon.ico {
        # will search for /var/www/project/src/favicon_abc.example.com.ico,
        # /var/www/project/src/favicon_def.example.com.ico, etc.
        alias /var/www/project/src/favicon_$host.ico;
    }
    ...

or even something more complex, e.g. (using regex named capture):

server {
    ...
    server_name ~(?<subdomain>.*)\.example\.com$;
    ...
    location = /favicon.ico {
        # will search for /var/www/project/src/favicon_abc.ico,
        # /var/www/project/src/favicon_def.ico, etc.
        alias /var/www/project/src/favicon_$subdomain.ico;
    }
    ...

or use map directive to hardcode the list of matches (should be defined in http context rather than server one):

map $host $icon {
    abc.example.com  favicon_abc.ico;
    def.example.com  favicon_def.ico;
    ...
    default          favicon.ico; # if none of above match
}
server {
    ...
    server_name example.com *.example.com;
    ...
    location = /favicon.ico {
        alias /var/www/project/src/$icon;
    }
    ...

Moreover, you can use the include directive and populate such a list using some third party tools including it afterwards to nginx config.

Upvotes: 1

Related Questions