NGINX Rewrite Subdomain to Path

09 Mar 2016

In this post I show you how to rewrite subdomain requests to a path.

This is a common requirement if a client or business wants to change a blog or API domain name scheme.

We will change blog.mydomain.com and api.mydomain.com to mydomain.com/blog and mydomain.com/api respectively.

Old Route ==> New Route
blog.mydomain.com ==> mydomain.com/blog
api.mydomain.com ==> mydomain.com/api
#This server block runs when a HTTP request comes in on port 80
#with the Host header set to blog.mydomain.com
#All paths from blog.mydomain.com is redirect to mydomain.com/blog

#Example
#A request to http://blog.mydomain.com/2016/12/A-Great-Blog-Post
#returns a 301 with the Location header set to
#http://mydomain.com/blog/2016/12/A-Great-Blog-Post
server {
    server_name blog.mydomain.com;
    listen 80;

    rewrite ^ http://mydomain.com/blog$uri permanent;

    access_log /var/log/nginx/blog-access.log;
    error_log  /var/log/nginx/blog-error.log;
}
#This server block runs when a HTTP request comes in on port 80
#with the Host header set to api.mydomain.com
#All paths from api.mydomain.com is redirect to mydomain.com/api

#Example
#An API request to http://api.mydomain.com/users gets a 301
#response with the Location header set to
#http://mydomain.com/api/users
server {
    server_name api.mydomain.com;
    listen 80;

    rewrite ^ http://mydomain.com/api$uri permanent;

    access_log /var/log/nginx/api-access.log;
    error_log  /var/log/nginx/api-error.log;
}

In these two server block examples, the access_log and error_log write to their own files.

I think these two examples will help migrate a blog hosted with NGINX or switching your API naming conventions.

It will get you started in the right direction for other NGINX rewrite subdomain to path needs.