7

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.

Quintin Par
  • 4,373
  • 11
  • 49
  • 72
  • Presuming all URLs and keep the relative path, you should be able to just add `rewrite ^/(.*)$ /blog/$1 redirect` to the top of your server block. – cyberx86 Nov 27 '11 at 06:15
  • @cyberx86 Infinite redirect loop, that. – Shane Madden Nov 27 '11 at 06:24
  • Now that was just careless of me - I should know better. Replacing, 'redirect' with 'last' doesn't generate an infinite loop, but still isn't quite ideal (it keeps the URL, but serves the right file). – cyberx86 Nov 27 '11 at 06:50
  • solution shared in this link worked for me: – Ozay Duman Nov 22 '16 at 08:07

4 Answers4

8
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;
}
Shane Madden
  • 114,520
  • 13
  • 181
  • 251
5

try this instead:

location = / {
      return 301 /blog/;
 }

The key here is '=' symbol.

Ozay Duman
  • 151
  • 1
  • 2
1

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.

0

for the just the home page and nothing else, i would use:

location / {           
    rewrite ^/$ /blog/ redirect;
}

anything else, like /foo/ would not be redirected to /blog/ .