Nginx Redirect

DateReadtime 1 minutes Tags

Problem

Recently I purchased a domain to replace my no longer free subdomain provided by dyndns. I wanted to redirect all of my content from the subdomain to my new domain. Easy. However, I also wanted the root landing page to display information about the move rather than simply throwing a 301.

So basically I want '/' to serve a page. And I want '/*' to be redirected to the new domain.

Solution

location / {
     if (!-e $request_filename) {
         rewrite ^ http://www.example.com$request_uri permanent;
     }
     alias /var/www/example.net/;
 }

Additional Info

To check the response of the server I choose to use curl. For example:

$  curl -I example.net/
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.1 (Ubuntu)
Date: Sun, 29 Jun 2014 15:28:15 GMT
Content-Type: text/html
Content-Length: 193
Connection: keep-alive
Location: http://www.example.com/

Sources

A handy faq on rewrites in nginx that I found to be very helpful.

I found a serverfault question that seemed promising, but it was specifically looking for two 301s to different places. After replacing one of the 301s with an 'alias' directive, all of the pages including '/' redirected.

Additionally, I found a relavent stackoverflow question. It seemed to rewrite all the urls to '/' rather than rewriting to a matching uri on the new domain.