Search code examples
http-redirectnginxsubdomainwildcard-subdomain

Nginx redirect for single page on single subdomain while using wildcard subdomains


I have a server block that uses wildcard subdomains, example *.example.com. I need to redirect a single page on a single subdomain to a different page, while processing all other requests normally. What's the most efficient way to handle this?

Server block looks something like this:

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

And I need this behavior:

http://baseball.example.com/test.php -> http://baseball.example.com/new-page

http://football.example.com/test.php -> no redirect

http://basketball.example.com/test.php -> no redirect


Solution

  • The most efficient way, from a processing perspective, would be to create a separate server block for the special case. As most of the configuration would be the same for both server blocks, you could use an include statement to read it from a separate file.

    For example:

    server {
        listen 80;
        server_name *.example.com;
        include /path/to/common.config;
    }
    server {
        listen 80;
        server_name baseball.example.com;
        location = /test.php {
            return 301 /new-page;
        }
        include /path/to/common.config;
    }
    

    See this document for more.