Posted on in #laravel-forge #nginx

Previously my old site hosted quite a number of really old blog posts, most recent was 2013 with the majority in 2008 when I was primarily developing in CakePHP. I wanted a clean slate (as do all devs!) so decided not to port them over or bother with creating an archive. By default on Forge when setting up SSL everything gets redirected to it's https counterpart, for old blog posts the initial server response was a 301 redirect (http -> https) then a 404 as the page wasn't found.

To keep things clean and indicate to Google that those pages have been removed I wanted to immediately serve a 404. I did something similar to serve 404s for old subdomains so using the same custom before config file I added a new server block for a specific post:

server {
    listen 80;
    listen [::]:80;

    server_name .jamesfairhurst.co.uk;
    location = /posts/view/old_post_url {
       return 404;
    }
}

This worked however it broke other page redirects it should have caught, I found a great article detailing server & location blocks which was super handy not being too familiar with nginx. Using the ^~ modifier caught all /posts/view/* urls and I also needed to add the / location block as a fallback for http -> https redirects taken from Forge's ssl_redirect.conf file.

server {
    listen 80;
    listen [::]:80;

    server_name .jamesfairhurst.co.uk;

    location ^~ /posts/view {
        return 404;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

After making changes run sudo service nginx reload to make the new changes active, and finally test the urls either in the browser or be fancy and use the command line. Instead of cURL I've been using HTTPie which is a super nice command line HTTP client:

[jamesfairhurst:~]$ http --headers http://www.jamesfairhurst.co.uk/posts/view/old_post_url
HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Length: 153
Content-Type: text/html
Date: Thu, 11 Apr 2019 08:34:20 GMT
Server: nginx/1.15.8