Nginx – How to redirect root to subdirectory while maintaining URL in the address bar

nginxredirectrewriteurl

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;
        }
}

Best Answer

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.

Related Topic