WordPress permalinks in nginx


WordPress generally works out-of-the box on nginx. The posts load fine, the functions in the dashboard work pretty well, until you come to the permalinks. If you are on Apache, with mod_rewrite, WordPress will automatically add the required rewrite rules to your .htaccess file for permalinks to work. But for nginx, you have to add the rules manually.

Moreover, when WordPress detects that mod_rewrite is not loaded (which is the case with nginx), it falls back to using PATHINFO permalinks, which inserts an extra ‘index.php’ in front. This hasn’t been much of a problem for me as I have been using the custom structure option to remove the index.php. It has been working fine for me. (Screenshot below)

Apart from that, you will also need to edit your nginx configuration file to make the permalinks work. We will use the try_files directive (available from nginx 0.7.27+) to pass URLs to WordPress’s index.php for them to be internally handled. This will also work for 404 requests.

  • If your blog is at the root of the domain (something like http://www.myblog.com), find the “location /” block inside the configuration file, and add the following line to it.
    [bash]try_files $uri $uri/ /index.php?q=$uri&$args;[/bash] It should look like this after the edits :

    [bash] location / {
    index index.php index.html index.htm;
    try_files $uri $uri/ /index.php?q=$uri&$args;
    }[/bash]

    • If your blog is in a subfolder (say /blog), you’ll have to add an extra “location /blog/” block to your configuration file :
      [bash] location /blog/ {
      try_files $uri $uri/ /blog/index.php?q=$uri&$args;
      }[/bash]

    After you have finished making the changes in the configuration file, reload the nginx configuration by :

    [bash]nginx -s reload[/bash]

    WordPress’ pretty permalinks should work fine now.