4

I have an nginx setup with folder structure like this:

- www
  |- splash
  |- blog

www is the root folder.

I would like to redirect users who access http://example.com to the splash folder.

But I don't want the URL in the address bar to change to http://example.com/splash.

The URL in the address bar should still be http://example.com.

This rule should only apply when user accesses the root folder.

Meanwhile accessing the blog folder will be as usual via: http://example.com/blog.

How do I achieve this? So far my conf is as follow: (they don't work btw, the URL is changed)

server {
        listen 80;
        server_name www.example.com;
        root /www;
        location = / {
                rewrite ^/(.*)$ splash/$1 permanent;
        }
}
1

3 Answers 3

1

Each context can have its own root.

Since you have a location context, just change the root.

Eg.

location = / {
    root /www/splash;
}

Documentation is available here. The example given in the documentation is:

location  /i/ {
  root  /spool/w3;
}

A request for "/i/top.gif" will return the file "/spool/w3/i/top.gif".

So essentially, almost a copy of that, except you have the = for an exact match in location.


If there is a file called /splash/blog, do you want that url to go to /splash/blog or /blog?

Another way to prioritize files is using try_files. For example:

location / {
    try_files /splash/$uri $uri =404;
}

In this case, if there is a matching file in /splash, that's what will be shown, otherwise $uri is shown instead, or in the last case, a 404 error.

1
  • I've tried this scenario, but in this case if I add more folders in the root in the future, I have to manually update the config. Can I somehow set it that if / then set root to somefolder. And else, set root to anotherfolder?
    – Goni
    Jun 13, 2013 at 9:22
1

This one worked for me if I got your situation right:

location ~/splash.* {
    return 200 "The request was $uri";
}

location / {
    rewrite ^/$ /splash/ last;
    root   /usr/share/nginx/html;
    index  index.html index.htm;
}

From Nginx docs

last stops processing the current set of ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI;

I didn't want to create directory /splash/ so I just told Nginx to respond with hardcoded text. You may replace it with required directives.

0

That's all ...

server {
        listen 80;
        server_name www.mysite.com;
        root /www;

        location = / {
                root /www/splash;
        }

        location / {
                root /www;
        }


}
2
  • It doesn't work. Accessing http://mysite.com still sees the content of /www. Any other ideas?
    – Goni
    Jun 13, 2013 at 10:06
  • show your full config, please
    – cadmi
    Jun 15, 2013 at 13:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .