Correct Nginx try_files syntax with query params

With WordPress sites and Nginx servers, you may have used one of the following try_files directives…

try_files $uri $uri/ /index.php;
try_files $uri $uri/ /index.php?$args;

Both are incomplete. With the first method, arguments are not passed. With the second method, question mark is present, even when there are no query parameters.

A complete solution is to use the following…

try_files $uri $uri/ /index.php$is_args$args;

$is_args checks, if $args is empty. If empty, the value of $is_args becomes empty. Otherwise “?”. Isn’t that genius!

However, if you have large number of vhosts, then it may be time-consuming to go through every vhost to update this change. Here’s a little one-liner to do the same…

sed -i '/try_files/ s/index.php;/index.php$is_args$args;/' *
sed -i '/try_files/ s/index.php?$args;/index.php$is_args$args;/' *

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s