Nginx seamless redirect, subdomain + subfolder

April 8, 2016 914 views
Nginx DNS CentOS


I’ve been trying lately to do two things on my server:

  • Redirect the url
  • Rewrite the url

The server is running on nginx.

My domain ( is set to get html files at the following root: /usr/share/nginx/html.
The redirect works fine with this added to the /etc/nginx/nginx.conf file:

server {
    location = / {
        return 301 /folderone/foldertwo/;

My problem comes when this happens. It logically redirects the user via a url redirect. So the browser is no longer showing but, which makes perfect sense.
Now what i’m trying to do is rewrite this url and remove those two folders from it to be back at from a visual point of view.

I’ve tried several things, among:

  • Setting the root of the server directive at /usr/share/nginx/html/folderone/foldertwo
  • Adding rewrite ^/folderone/foldertwo/(.*) /$1; in the same location block as the return
  • Adding rewrite into another location block like so: location = /folderone/foldertwo/ { rewrite... }
  • Adding a location block with a condition: location / { if ($http_host ~ "^"){ rewrite ^(.*)$$1 redirect; } }
  • Adding a specific location rewrite (which breaks it all): location /issue { rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent; } I’m wondering if this can be achieved since i’m trying to redirect to a specific folder and then almost “redirect” to the root.

If possible, should the rules be in the same server directive? Same location block? Is an alias the solution?


1 Answer


In this case, a simple rewrite rule will do.

server {
    rewrite ^/$ /folderone/foldertwo;

By default, rewrite performs the redirection internally without informing the user about it. As a result of that, the URL will stay as while actually serving Keep in mind that any relative URLs will be relative to /, not /folderone/foldertwo.

Have another answer? Share your knowledge.