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.

4
  • 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 6:15
  • @cyberx86 Infinite redirect loop, that. – Shane Madden Nov 27 '11 at 6: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 6:50
  • solution shared in this link worked for me: <serverfault.com/a/677337/386872> – Ozay Duman Nov 22 '16 at 8:07
7
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;
}
3

try this instead:

location = / {
      return 301 /blog/;
 }

The key here is '=' symbol.

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/ .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.