Nginx: Redirect everything except the home page

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

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

However, I wanted the root of philipjohn.me.uk to show a special page, not redirect to philipjohn.blog.

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


server { listen 80; listen [::]:80; server_name philipjohn.me.uk; root /var/www/philipjohn.me.uk/www/; index index.html; location = /index.html { try_files $uri $uri/ =404; } location ~ ^/.+$ { return 301 http://philipjohn.blog$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 philipjohn.blog.

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


Posted

in

by

Comments

Leave a Reply

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