Tag: permalinks

  • Changing WordPress permalink structure on Nginx

    I decided to follow Joost de Valk’s (of Yoast fame) advice for ideal permalink structure and switch my permalinks from year/month/day/postname to postname.  Of course this means that any links already out there and any search engine indexes will now point to the wrong place.  Time for some redirects!

    There are plenty of guides and tools available to help you if you decide to change your permalink structure whilst using Apache with its .htaccess files to host WordPress, however I use Nginx so I needed another approach.

    The redirect is actually very simple; first detect that the URL is in the format using a regular expression.

    The regular expression below checks that the url contains a slash followed by four numbers, followed by a slash, followed by two numbers, followed by another slash, followed by another 2 numbers, followed by yet another slash, followed by anything.  Which will match my previous permalink structure (i.e. www.ukitblog.co.uk/2013/07/22/deploying-airserver/‎)

     ^/([0-9]{4})/([0-9]{2})/([0-9]{2})/(.*)$

    And then, take the 4th (and final) part of the URL and append it to the sites URL

    rewrite "^/([0-9]{4})/([0-9]{2})/([0-9]{2})/(.*)$" http://www.ukitblog.co.uk/$4 permanent;

    Giving a complete rule of:

    location ~ "^/([0-9]{4})/([0-9]{2})/([0-9]{2})/(.*)$" {
     rewrite "^/([0-9]{4})/([0-9]{2})/([0-9]{2})/(.*)$" http://www.ukitblog.co.uk/$4 permanent;
    }

    It’s very easy to adjust the above snippet to apply to other styles of previous redirects, give me a shout in the comments if you need any help.

    Also, if the change is only temporary you can use the word redirect instead of permanent to issue a 302 temporary redirect rather than a 301 permanent redirect.

    The rule just needs to be inserted in your Nginx configuration for the specific site, probably located at /etc/nginx/sites-available/domainname.tld