Today I had an issue where I was trying to debug a problem with an nginx configuration, I came up with a simple trick. One of the hardest parts of nginx configurations, especially with rewrites, is you might not know which “location” directive is not working as expected.
In PHP, sometimes you would just add something like this:
[php]
echo "I’m here!";
exit();
[/php]
However, in Nginx configuration files, it isn’t as easy…
… or is it?
One thing that works well is the rewrite directive. You can append variables to the URL to be rewritten. Another great thing is a rewrite statement can go just about anywhere. So lets say we were trying to debug this location statement:
location ~ /api/.*.php$ { include /etc/nginx/fastcgi_params; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /path/to/www/$fastcgi_script_name; }
Now lets say its returning a 404, and I’m not 100% sure what the actual value of $fastcgi_script_name is. I can add this to it:
location ~ /api/.*.php$ { ## ADD HERE redirect ^ http://www.google.com/?q=$fastcgi_script_name last; break; include /etc/nginx/fastcgi_params; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /path/to/www/$fastcgi_script_name; }
This will redirect your HTTP request to Google.com and put the value in the query textfield. Bingo, I can easily see the actual value! Pretty helpful when you have a large, complex server definition.
Nice trick, but it should be rewrite instead of redirect:
rewrite ^ http://www.google.com/?q=$fastcgi_script_name last; break;
LikeLike
Thanks, very helpful in understanding the flow of rewrites and what not! Please do update the post to reflect Dirk’s correction.
The add_header directive works well when using this trick:
# Equivalent of var_dump(…);die(__LINE__);
#rewrite ^ http://www.google.com/?line=343&q=foo last; break;
#add_header X-nginx-request_uri $request_uri;
#add_header X-nginx-uri $uri;
#add_header X-nginx-args $args;
#add_header X-nginx-fastcgi_script_name $fastcgi_script_name;
#add_header X-nginx-fastcgi_path_info $fastcgi_path_info;
Found it easier to read each variable as it’s own header variable than in the querystring 🙂
LikeLike
Correction on my own comment – should be:
# Equivalent of var_dump(…);die(__LINE__);
#add_header X-nginx-request_uri $request_uri;
#add_header X-nginx-uri $uri;
#add_header X-nginx-args $args;
#add_header X-nginx-fastcgi_script_name $fastcgi_script_name;
#add_header X-nginx-fastcgi_path_info $fastcgi_path_info;
#rewrite ^ http://www.google.com/?line=343&q=foo last; break;
For the novice: Use “curl -v” or Chrome Developer Tools to see the headers.
LikeLike
Very useful, thanks.
LikeLike