Redirect Only the Root URL Path for Nginx and Apache

A client of mine has a website that was once their primary website. They had about 70+ gigabytes of files for webinars, lectures and ebooks for download on the site. But over time they migrated all their traffic to a new domain with a new design and store. The old domain remained in use but it was used for downloads only. So the question was brought up, how do you redirect only the root URL path of the site. This would allow you to send all the traffic to the root of the domain to their primary site but still allow the downloads.

Redirect only the root URL path for Nginx

Nginx was the natural choice this site with all of the static download content. So I began to search for different options to allow me to redirect only the root url path. While searching I found this page that outlines the location directive to be added into my Nginx config. The directive is this:

location = / {       
     return 301 https://new-site.com/feature-page/; 
}

The “location = /” section tells Nginx to match all queries that only come to the root of the site. And “return 301 https://new-site.com/feature-page/;” tells Nginx to perform a 301 redirect to new-site.com. You can perform a 302 redirect if you prefer by switching the number from 301 to 302.

The directive above can be added in anywhere in your “Server {}” section of the Nginx config.

Redirect only the root URL path for Apache

We don’t want anyone to feel left out. So for all you apache web server lovers out there here is the config to redirect only the root of Apache. I found a good example of how to accomplish this here.

RewriteEngine on 
RewriteCond %{HTTP_HOST} mysite\.com [NC] 
RewriteCond %{REQUEST_URI} ^/$ 
Rewriterule ^(.*)$ http://mysecondsite.com/ [L,R=301]

What do these configuration settings mean? “RewriteEngine on” ensures that Apache’s Rewrite Engine is working. The next line adds a condition to the rewrite rule. It specifies that the request should compare what the server sees as the HTTP_HOST of the request against “mysite.com”. The “[NC]” indicates that comparison should be made in a case insensitive manner.

The next rule checks the REQUEST_URI to see if it matches only the root with nothing after it. When both those conditions are met the request will be redirected to http://mysecondsite.com/. The “[L,R=301]” indicates that the redirect should be a 301 and this is the “Last” rule to check.

So any request to exactly “mysite.com/” will automatically be redirected to “http://mysecondsite.com/”.