Nginx: Rewrite from base domain to a sub directory

I have a blog hosted at http://site.com/blog.

How do I instruct nginx to rewrite requests from site.com to site.com/blog?

This should not be permanent.


location = / {
    rewrite ^ http://site.com/blog/ redirect;
}

This'll just do requests specifically for the root. If you need to catch everything (redirect http://site.com/somearticle/something.html to http://site.com/blog/somearticle/something.html), then you'll need something more involved:

location /blog/ {
    # Empty; this is just here to avoid redirecting for this location,
    # though you might already have some config in a block like this.
}
location / {
    rewrite ^/(.*)$ http://site.com/blog/$1 redirect;
}

try this instead:

location = / {
      return 301 /blog/;
 }

The key here is '=' symbol.


This has not worked for me. This is what has worked:

  1. Open the NGINX configuration file for your site. Inside of the server block, add the path to your root directory and set the priority order for files:

    root /mnt/www/www.domainname.com;
    index  index.php index.html index.htm;
    
  2. Create an empty location block before all your other location blocks:

    location /latest {
    # Nothing in here; this is to avoid redirecting for this location
    }
    
  3. Comment out the root directory directive in your location / {} block and add the redirection so it looks like this:

    location / {
    # root   /mnt/www/www.domainname.com;
    index  index.php index.html index.htm;
    rewrite ^/(.*)$ http://www.domainname.com/latest/$1 redirect;
    }
    
  4. Make sure that your location ~ .php$ block points its root to

    root /mnt/www/www.domainname.com;
    

This fixed it for me.