Nginx: Redirect everything except the home page

Recently I moved this blog to, making a sort of “homepage” pointing to my various online presences.

Previously, my blog was at so as well as changing the URL (which was made easy by WP-CLI) I need to redirect all URLs to

However, I wanted the root of to show a special page, not redirect to

After much Googling and some help from Nicola Heald I finally had a working Nginx config:

server { listen 80; listen [::]:80; server_name; root /var/www/; index index.html; location = /index.html { try_files $uri $uri/ =404; } location ~ ^/.+$ { return 301$request_uri; } }

They key bits are the two location blocks. The first uses location = /index.html because Nginx interally redirects requests for the root into an index file, according to the index directive.

That first location block has the effect of telling Nginx to look inside the root folder for the index.html, or return a 404.

The second location block only then gets called if the request is not for the root index.html file. This block simply grabs the request string and passes it onto

Simple! (And only took me several hours to get right 😉 )

Leave a Reply

Your email address will not be published. Required fields are marked *