Seán Hayes
Seán Hayes

Reputation: 4360

Nginx: Only use server block if location matches

I have a catch all server block like this:

server {
    listen      80 default_server;
    server_name _;

    location /blog{
        # pass request to ghost
    }
    location /{
        # pass request to custom node app
    }
}

It passes to the custom node app, which verifies the requested domain, protocol, and path, and issues a single 301 redirect if necessary; we do this to minimize 301 redirects, for SEO purposes.

I also need my ghost blog to only be served at https://www.exmaple.com/blog. I added the following block:

server {
    listen      80;
    server_name example.com;

    location /blog {
        return 301 https://www.example.com$request_uri;
    }
}

so that requests to the naked domain would get redirected. But now requests to example.com return the default Nginx index.html page. How do I prevent that? I'd like to avoid using if.

Upvotes: 1

Views: 1078

Answers (1)

miah
miah

Reputation: 10433

You need to have a catch-all in the naked domain server block that routes to the node application

server {
    listen      80;
    server_name example.com;

    location /blog {
        return 301 https://www.example.com$request_uri;
    }

    location /{
        # pass request to custom node app
    }
}

Upvotes: 2

Related Questions