WordPress permalinks with Nginx

If you are on Apache(mod_rewrite), WordPress will automatically add the required rewrite rules to your .htaccess file for permalinks to work. Just add code generated by WordPress in .htaccess, and its done. But for nginx, you have to add the rules manually in the nginx conf file.

But the problem is when WordPress detects that mod_rewrite is not loaded (which is this case, nginx), it falls back to using PATHINFO permalinks, which inserts an extra ‘index.php’ in front. This will cause the problem for me as I want to remove the index.php from the permalinks.

Permalink Setting

So you need to edit your nginx configuration file to make the permalinks work. We will use the try_files directive to pass URLs to WordPress’s index.php for them to be internally handled.

If your blog is at the root of the domain (something like www.blog.com), find the location / block inside the configuration file, and add the following line to it.
[shell]try_files $uri $uri/ /index.php?q=$uri&$args;[/shell]

Here, Nginx checks for the existence of a file at the URL ($uri), then for a directory ($uri/). If it doesn’t find a directory or a file, it performs an internal redirect to /index.php passing the URL as PATHINFO.

It should look like this after the edits :
[shell]
location / {
index index.php index.html index.htm;
try_files $uri $uri/ /index.php?q=$uri&$args;
}
[/shell]

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

After you have finished making the changes in the configuration file, reload the nginx configuration:
[shell]nginx -s reload[/shell]

The permalinks should be working fine now.

Any Comments?